[英]Can I type assert a slice of interface values?
I am trying to type assert from a []Node
, to []Symbol
. 我试图从
[]Node
键入断言,到[]Symbol
。 In my code, Symbol
implements the Node
interface. 在我的代码中,
Symbol
实现了Node
接口。
Here is some surrounding code: 这是一些周围的代码:
43 func applyLambda(args []Node, env Env) Node {
44 if len(args) > 2 {
45 panic("invalid argument count")
46 }
47 fixed, rest := parseFormals(args.([]Symbol))
48 return Func{
49 Body: args[1],
50 FixedVarNames: fixed,
51 RestVarName: rest,
52 }
53 }
Here's the error I get: 这是我得到的错误:
./builtins.go:47: invalid type assertion: args.([]Symbol) (non-interface type []Node on left)
I'm sure there's a good reason for this. 我确信这是有充分理由的。 What's the best way to proceed?
什么是最好的方法?
In saying x.(T)
variable x
should be of interface type, because only for variables of type interface dynamic type is not fixed. 在说
x.(T)
变量x
应该是接口类型,因为只有类型接口的变量动态类型不固定。 And while Node
is an interface, []Node
is not. 虽然
Node
是一个接口, []Node
不是。 A slice is a distinct, non-interface type. 切片是一种独特的非接口类型。 So it just doesn't make sense to assume a slice of interface values is an interface too.
因此,假设一片接口值也是一个接口也没有意义。
Type Node
has a clear definition in your code and thus is an interface. 类型
Node
在您的代码中具有明确的定义,因此是一个接口。 You have specified the list of methods for it. 您已为其指定了方法列表。 Type
[]Node
isn't like that. 类型
[]Node
不是那样的。 What methods does it define? 它定义了哪些方法?
I understand where your are coming from with this. 我明白你的来源是什么。 It may be a useful shortcut, but just doesn't make sense.
它可能是一个有用的捷径,但是没有意义。 It's kind of like expecting
syms.Method()
to work when syms
's type is []Symbol
and Method
is for Symbol
. 这有点像期待
syms.Method()
在syms
的类型是[]Symbol
和Method
用于Symbol
。
Replacing line 47 with this code does what you want: 用这段代码替换第47行可以实现你想要的:
symbols := make([]Symbol, len(args))
for i, arg := range args { symbols[i] = arg.(Symbol) }
fixed, rest := parseFormals(symbols)
Go does not allow this. Go不允许这样做。 You need to convert
Node
to Symbol
individually. 您需要单独将
Node
转换为Symbol
。
The reason why it isn't allowed is that []Node
and []Symbol
have different representations, so the conversion would need to allocate memory for []Symbol
. 不允许它的原因是
[]Node
和[]Symbol
具有不同的表示,因此转换需要为[]Symbol
分配内存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.