Dlang 语言 f_range_forach 自定义遍历错误解决:类型转换和语法问题
在代码中存在一些语法错误和类型转换错误,以下是修正后的代码:
import std.stdio;
import std.conv:to;
import std.algorithm;
struct Person
{
int age;
string name;
// 定义Range类型,用于遍历Person结构体
struct ByKeyValueRange
{
string[] keys = ['age', 'name'];
const(Person)* p;
size_t index;
bool empty() const pure @safe {
return index >= keys.length;
}
void popFront() @safe {
++index;
}
auto front() const @safe {
return Entry(keys[index], p);
}
}
struct Entry
{
string key;
const(Person)* p;
@property
string val() const @safe {
return getFieldAsString(p, key);
}
}
ByKeyValueRange byKeyValue() const @safe
{
return ByKeyValueRange(&this);
}
auto byKey() const @safe
{
return byKeyValue.map!(entry => entry.key);
}
auto byValue() const @safe
{
return byKeyValue.map!(entry => entry.val);
}
}
static string getFieldAsString(const(Person)* p, const string key) @safe
{
if (key == 'age')
return to!string(p.age);
else if (key == 'name')
return p.name;
else
return '';
}
void main()
{
Person p = Person(30, 'Alice');
writeln('byKeyValue:');
foreach (entry; p.byKeyValue())
writeln(entry.key, ': ', entry.val);
writeln('\nbyKey:');
foreach (key; p.byKey())
writeln(key);
writeln('\nbyValue:');
foreach (value; p.byValue())
writeln(value);
}
主要的修改有:
- 在
ByKeyValueRange中将Person*改为const(Person)*,因为在byKeyValue函数返回该结构体时,需要传入const Person*类型的指针。 - 在
byKeyValue、byKey和byValue函数中,都添加了const修饰符,因为这些函数不会修改Person结构体中的数据。 - 在
getFieldAsString函数中,也需要传入const(Person)*类型的指针。
原文地址: https://www.cveoy.top/t/topic/olTR 著作权归作者所有。请勿转载和采集!