开发者

Assigning to map in golang

In the following go snippet, what am I doing wrong?

type Element interface{}

func buncode(in *os.File) (e Element) {
    <snip>
    e = make(map[string]interface{})
    for {
        var k string = buncode(in).(string)
        v := buncode(in)
        e[k] = v
    }
    <snip>
}

Compiling gives me this error:

gopirate.go:38开发者_StackOverflow: invalid operation: e[k] (index of type Element)

Double ewe T eff?


In the buncode function you declare e Element, where type e Element interface{}. The variable e is a scalar value, which you are trying to index.

Types

The static type (or just type) of a variable is the type defined by its declaration. Variables of interface type also have a distinct dynamic type, which is the actual type of the value stored in the variable at run-time. The dynamic type may vary during execution but is always assignable to the static type of the interface variable. For non-interface types, the dynamic type is always the static type.

The static type of e is Element, a scalar. The dynamic type of e is map[string]interface{}.

Here's a revised, compilable version of your code.

type Element interface{}

func buncode(in *os.File) (e Element) {
    m := make(map[string]interface{})
    for {
        var k string = buncode(in).(string)
        v := buncode(in)
        m[k] = v
    }
    return m
}

Why are you making the recursive calls to buncode?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜