为什么我不能将const(char)*连接到D中的字符串?

Ral*_*zky 6 string d concatenation

代码

string bar = "Hello ";
const(char) * foo = "world!";
bar ~= foo;
Run Code Online (Sandbox Code Playgroud)

无法在第三行编译.为什么?我有什么优雅的替代品?

错误输出是Error: cannot append type const(char)* to type string.

Pet*_*der 11

不要用const(char)*

string bar = "Hello ";
string foo = "world!";
bar ~= foo;
Run Code Online (Sandbox Code Playgroud)

D中的字符串文字属于类型,除了与C代码接口外string,您不应该使用a const(char)*.

D不允许连接的原因是因为const(char)*不是字符串,在任何意义上都是字.D中的字符串是immutable(char)[](aliasd by string).A const(char)*只是指向常量字符的指针.与C和C++不同,没有隐含的空终止符,所以D不能也不会假设有一个.

如果由于某种原因你绝对必须使用a const(char)*并且你知道它是空终止的,那么你可以const(char)[]通过切片来制作它,然后你可以附加到string:

string bar = "Hello ";
const(char)* foo = "world!";
bar ~= foo[0..strlen(foo)];
Run Code Online (Sandbox Code Playgroud)

  • 切片`foo`不会给你一个`string`,而是`const(char)[]`.它仍然与`string bar`连接兼容,但是如果你试图在`string`变量中存储切片`foo`的结果,你会得到一个错误. (2认同)