Can I type assert a slice of interface values?

前端 未结 2 871
情歌与酒
情歌与酒 2020-12-09 16:36

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

Here is

相关标签:
2条回答
  • 2020-12-09 17:18

    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)
    
    0 讨论(0)
  • 2020-12-09 17:25

    Go does not allow this. You need to convert Node to Symbol individually.

    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.

    0 讨论(0)
提交回复
热议问题