D 编程语言 char 数组
这听起来可能真的很愚蠢。 但我在 D 编程语言方面遇到了一个奇怪的问题。 当我尝试创建一个像这样的新数组时:
import std.stdio;
void main()
{
char[] variable = "value";
writefln(variable);
}
DMD 编译器总是给我这个错误:
test.d(5):错误:不能隐式 转换类型的表达式(“值”) 不变(char[5u])到 char[]
知道为什么吗? 我使用的是 Ubuntu 2.014 alpha(此处)。
This may sound really stupid. but I've got a strange problem with the D programming language. When I try to create a new array like this:
import std.stdio;
void main()
{
char[] variable = "value";
writefln(variable);
}
The DMD compiler always gives me this error:
test.d(5): Error: cannot implicitly
convert expression ("value") of type
invariant(char[5u]) to char[]
Any idea why? I'm using the 2.014 alpha (available here) for Ubuntu.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我正在搜索指南的数组部分,这可能会有所帮助:
字符串是字符数组。 字符串文字只是编写字符数组的一种简单方法。 字符串文字是不可变的(只读)。
来自此处。
I was searching around the arrays section of the guide, this may help:
A string is an array of characters. String literals are just an easy way to write character arrays. String literals are immutable (read only).
From here.
基本上,归根结底就是字符串文字存储在内存的只读部分中。
char[]
是“可变字符的可变数组”,如果对其进行写入,则会产生运行时崩溃。所以编译器真的想在这里保护你。
invariant(char)[]
的意思是“不变字符的可变数组”,这正是它的本质。PS:当您不需要它是
char[]
时,您可能需要使用auto
,如autovariable = "value"
。 让您不再思考它的类型:)Basically, what it comes down to is that string literals are stored in a read-only part of memory.
char[]
is "a mutable array of mutable characters", which would, if written to, generate a run-time crash.So the compiler is really trying to protect you here.
invariant(char)[]
means "a mutable array of invariant characters", which is exactly what it is.PS: When you don't need it to be a
char[]
, you might want to useauto
, as in,auto variable = "value"
. Frees you from thinking about its type :)使用 auto 并且不用担心类型是什么:
让编译器担心类型。
use auto and don't worry what the type is:
let the compiler worry about the type.
D 语言有两个主要版本。 一般来说,它们彼此不兼容,尽管可以编写代码来在两者中进行编译。
D1 是您提供的代码似乎是用它编写的。它没有不可变数组的概念,因此这是可行的。
D2 是您尝试将其编译为的内容,因此 2 开头是编译器版本号。 D2 特有的主要功能之一是 const 和不可变/不变数据引用的概念。
D2 中的字符串文字被归类为不可变数据,因此不能分配给 char[],而只能分配给
const(char)[]
或invariant(char)[]
(或 wchar 或 dchar 等效项)。string
是invariant(char)[]
的别名,为了方便或 D1 兼容性,您可能需要使用它。There are two main versions of the D language. They are, in general, mutually incompatible with each other, although code can be written to compile in both.
D1 is what the code you supplied seems to be written in. It doesn't have a concept of immutable arrays, hence this works.
D2 is what you are trying to compile it as, hence the 2 beginning the compiler version number. One of the main D2-specific features is this concept of const and immutable/invariant data references.
String literals in D2 are classed as immutable data, and therefore cannot be assigned to a char[], but only a
const(char)[]
orinvariant(char)[]
(or wchar or dchar equivalents).string
is an alias ofinvariant(char)[]
, which you may want to use either for convenience or for D1 compatibility.