在代码中存在一些语法错误和类型转换错误,以下是修正后的代码:

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);
}

主要的修改有:

  1. ByKeyValueRange 中将 Person* 改为 const(Person)*,因为在 byKeyValue 函数返回该结构体时,需要传入 const Person* 类型的指针。
  2. byKeyValuebyKeybyValue 函数中,都添加了 const 修饰符,因为这些函数不会修改 Person 结构体中的数据。
  3. getFieldAsString 函数中,也需要传入 const(Person)* 类型的指针
dlang语言以下代码报错提示f_range_forach自定义遍历d26 Error cannot implicitly convert expression thisp of type constPerson to Personf_range_forach自定义遍历d43 Error cannot implicitly convert expression &this of type Pers

原文地址: http://www.cveoy.top/t/topic/fF6q 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录