5

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: invalid operation: e[k] (index of type Element)

Double ewe T eff?

1 Answer 1

3

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?

Sign up to request clarification or add additional context in comments.

4 Comments

But I set it's type with the assignment from the make? I gathered from the spec on type assertions that the type would now be that of the "larger" type I'd assigned to it.
The recursive calls fetch the nested values for m. If you're interested, and have some idiomatic go-isms to propose, take a look here: code.google.com/p/erutor/source/browse/bencoding.py
@Matt (1) - The compiler doesn't track the dynamic type of an interface{} value, even if it can be statically known. You must use a separate variable with the correct type.
Are you sure this is going to compile ? You specify Element as a return value and you are returning map. I'm just curious if I'm missing something here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.