这段代码在使用 reversejoiner 函数时出现了编译错误,错误提示为:

/home/chenfa/dev_soft/dmd_all/usr/include/dmd/phobos/std/algorithm/iteration.d(2975): Error: static assert: The ElementyType of RoR 'dchar' must be an Inpu tRange (isInputRange!(ElementType!(dchar[]))). reverse_test.d(11): instantiated from here: joiner!(dchar[], string)

错误提示的意思是:在使用 reversejoiner 时,需要传入一个 InputRange 类型的参数,而代码中传入的是一个 dchar 数组,而 dchar 数组不是 InputRange 类型,所以编译器报错。

为了解决这个问题,需要将 dchar 数组转换为 InputRange 类型。可以使用 std.range.iota 函数将数组的下标范围转换为 InputRange 类型。修改后的代码如下:

import std.stdio;
import std.string;
import std.conv:to;
import std.array:array;
import std.algorithm:reverse,joiner;
import std.range:iota;

void main()
{
    string str = 'hello, world!';
    str = str.replace('o', '0').replace('l', '1').replace(',', '').replace('!', '');
    auto arr = str.array;
    arr.reverse;
    str = arr[iota(0, arr.length)].joiner('');
    writeln(str);  
}

修改后的代码中,我们首先将 str 转换为 dchar 数组,然后使用 iota 函数生成一个 InputRange 类型,表示数组的下标范围。最后,我们使用 joiner 函数将数组中的字符拼接成字符串。

通过这种方式,我们就将 dchar 数组转换为了 InputRange 类型,解决了编译错误。

D 语言代码编译错误:reverse 和 joiner 函数使用 InputRange 类型参数

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

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