我可以键入断言一部分接口值吗? [英] Can I type assert a slice of interface values?
问题描述
我正在尝试从 []Node
到 []Symbol
键入断言.在我的代码中,Symbol
实现了 Node
接口.
I am trying to type assert from a []Node
, to []Symbol
. In my code, Symbol
implements the Node
interface.
这里是一些周边代码:
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 }
这是我得到的错误:
./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?
推荐答案
话说x.(T)
变量x
应该是接口类型的,因为只针对变量类型接口动态类型不固定.虽然 Node
是一个接口,但 []Node
不是.切片是一种独特的非接口类型.所以假设接口值的一部分也是一个接口是没有意义的.
In saying x.(T)
variable x
should be of interface type, because only for variables of type interface dynamic type is not fixed. And while Node
is an interface, []Node
is not. 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
在你的代码中有明确的定义,因此是一个接口.您已经为其指定了方法列表.类型 []Node
不是那样的.它定义了哪些方法?
Type Node
has a clear definition in your code and thus is an interface. You have specified the list of methods for it. Type []Node
isn't like that. What methods does it define?
我了解您的出处.这可能是一个有用的捷径,但没有任何意义.这有点像期望 syms.Method()
在 syms
的类型是 []Symbol
和 Method
时工作> 代表符号
.
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
.
用此代码替换第 47 行即可:
Replacing line 47 with this code does what you want:
symbols := make([]Symbol, len(args))
for i, arg := range args { symbols[i] = arg.(Symbol) }
fixed, rest := parseFormals(symbols)
这篇关于我可以键入断言一部分接口值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!