问题描述
我正在尝试使用slice运算符从std.range获取take函数的返回值的分片。我的代码:
I'm trying to use the slice operator to obtain a slice of the return value of the take function from std.range. My code:
auto tempChunk = ['a', 'b', 'c', 'd'];
auto a = tempChunk.take(3);
writeln(a[0..2]);
在这种情况下,作为Take!R只是char []的别名,我希望这个编译。但是,编译器告诉我 Take!(char [])无法用[]
切片。再举一个例子:
As Take!R in this case is just an alias for char[], I'd expect this to compile. However, the compiler tells me that Take!(char[]) cannot be sliced with []
. Taking another example:
int[] arr1 = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
auto s = arr.take(5);
writeln(s[0..4]);
这将编译并运行,没有问题,打印[1、2、3、4、5] 。关于第一个示例为什么不起作用而第二个示例为什么不起作用,我完全感到困惑。
This will compile and run without a problem, printing [1, 2, 3, 4, 5]. I am completely confused at this point as to why the first example won't work, while the second does.
推荐答案
take 模板使用 hasSlicing 确定是否可以返回输入的片段而不是Take!R结构。检查实际的返回类型使它更加清晰:
take template uses hasSlicing to determine if slice of input can be returned instead of Take!R struct. Checking actual return types makes it a bit more clear:
import std.range, std.stdio;
void main()
{
auto chararr = ['a', 'b', 'c', 'd'];
auto a = chararr.take(3);
writeln( typeid(typeof(a)) );
auto intarr = [ 1, 2, 3, 4 ];
auto b = intarr.take(3);
writeln( typeid(typeof(b)) );
}
// Output:
// std.range.Take!(char[]).Take
// int[]
已进行切片明确指示为所有窄字符串返回 false -这些元素可能不代表单个字符,而是一个代码点(基于char和wchar的字符)。
hasSlicing is explicitly instructed to return false for all "narrow strings" - those, which element may not represent single character, but a code point (char and wchar based ones).
现在,这是我的猜测开始的地方,但我想这样做是为了防止意外生成格式错误的UTF-8和使用切片的Co字符串。如果您在char []中没有任何实际需要,最好使用dchar []。
Now, here is where my speculations start but I suppose it is done to prevent accidental creating of malformed UTF-8 & Co strings using slicing. Better to use dchar[] if you do not have any real need in char[].
这篇关于无法从D中的std.range切片Take!R吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!