我可以键入断言一个接口值的切片? [英] Can I type assert a slice of interface values?

查看:163
本文介绍了我可以键入断言一个接口值的切片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从 [] Node 中输入assert,以 [] Symbol 。在我的代码中, Symbol 实现了 Node 接口。

这是一些周围的代码:

  43 func applyLambda(args [] Node,env Env)Node {
44如果len(args)> 2 {
45 panic(无效参数计数)
46}
47 fixed,rest:= parseFormals(args。([] Symbol))
48 return Func {
49正文:args [1],
50 FixedVarNames:fixed,
51 RestVarName:rest,
52}
53}
  

$ b ./builtins.go:47:invalid type assertion:args。([] Symbol)(非接口类型[]节点在左边)

我相信这有一个很好的理由。 c>变量 x 应该是接口类型,因为只有接口动态类型的变量才是固定的。虽然 Node 是一个接口,但是 [] Node 不是。切片是一种独特的非接口类型。因此,假设一片接口值也是一个接口也没有意义。



类型节点在你的代码中有明确的定义,因此是一个接口。你已经为它指定了方法列表。类型 [] Node 不是那样。它定义了什么方法?



我明白你是从哪里来的。这可能是一个有用的捷径,但没有意义。这就好像期望 syms.Method() syms 的类型为 []符号方法用于符号



使用此代码替换第47行:

  symbols:= make([] Symbol ,len(args))
for i,arg:= range args {symbols [i] = arg。(Symbol)}
fixed,rest:= parseFormals(symbols)


I am trying to type assert from a []Node, to []Symbol. In my code, Symbol implements the Node interface.

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. 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 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?

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.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆