无法将常量(结构)类型附加到数组
在一个结构体中,Shape I 有一个函数:
...
import graphics.line;
struct Shape {
Line[] lines;
void addLine(Line l) {
lines ~= l;
}
}
Line 也是一个结构体,但是当我将“in Line l
”作为 addLine()
的参数声明时, 编译器出现错误:
shape.d(12):错误:无法附加类型 const(Line) 来输入 Line[]
奇怪的是我在另一个模块中有一段类似的代码,并且它有效......所以我的问题是,为什么编译器在这种情况下对此不满意?
In one struct, Shape I have a function:
...
import graphics.line;
struct Shape {
Line[] lines;
void addLine(Line l) {
lines ~= l;
}
}
Line is also a struct, but when I put "in Line l
" as the argument declaration for addLine()
,
the compiler bugs out with:
shape.d(12): Error: cannot append type
const(Line) to type Line[]
The weird thing is I have a similar piece of code in another module, and it works... So my question is, why is the compiler not happy with it in this case?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
基本上,这是否有效取决于您的结构具有哪些成员。
中
存储类相当于const作用域。所以,写
void addLine(in Line l)
表示l
是 const。由于const
是传递性,所有
Line l
结构成员也是const
。然而,
Shape
成员Line[]lines
不是const
。所以,你正在尝试将
const Line l
附加到非const
的内容。这是否是可能取决于 struct Line l 的所有成员的类型。如果全部
line
的成员具有值(复制)语义,此附加(这是一个分配)是可能的。如果任何一个成员具有(某些)参考语义(例如
指针被复制),这种附加不再可能。否则,你
可以将
const Line lc
放入addLines
中,但会得到一个非常量成员行
。通过这个,您可以使用引用语义更改值,也间接改变了原始
lc
的值,从而违反了const
保证,即 D 中const
的传递性。示例:
编辑: BTW,另一种使其工作的方法是更改
Line[]lines;
到const(Line)[]lines;
。该数组仅包含const
元素,并且可以在addLine
中附加const l
。Basically, whether this works depends on what members your struct has. The
in
storage class is equivalent to
const scope
. So, writingvoid addLine(in Line l)
means thatl
is const. And sinceconst
istransitive, all
Line l
struct members areconst
, too.The
Shape
memberLine[] lines
is however notconst
. So, you are trying toappend a
const Line l
to something that is notconst
. Whether this ispossible depends on the types of all members of the
struct Line l
. If allmembers of
line
have value (copy) semantics, this appending (which is anassignment) is possible. If any one member has (some) reference semantics (e.g.
a pointer gets copied), this appending is no longer possible. Otherwise, you
could give a
const Line lc
intoaddLines
, but would get a non-const memberof
lines
. Through this, you could change the value with reference semantics,changing the value of the original
lc
indirectly, too, thereby violating theconst
guarantee, namely the transitivity ofconst
in D.Example:
Edit: BTW, another way to make it work is to change
Line[] lines;
toconst(Line)[] lines;
. Than the array contains onlyconst
elements, and the appending of aconst l
inaddLine
is possible.