elquatro
elquatro

Reputation: 11

Interface{} type understanding

Can't understand the problem:

    var foo interface{}
    foo = make(map[string]int)  
    fmt.Println(foo)  // map[]

but

    foo["one"] = 1

prog.go:10: invalid operation: foo["one"] (index of type interface {}) [process exited with non-zero status]

Why is that?

Upvotes: 1

Views: 205

Answers (1)

ANisus
ANisus

Reputation: 77925

foo is of type interface{}. It might contain a map, but it is still an interface.

In order to do a map lookup, you first need to make a type assertion:

foo.(map[string]int)["one"] = 1

More about type assertion can be found in the Go specifications:

For an expression x of interface type and a type T, the primary expression
x.(T)
asserts that x is not nil and that the value stored in x is of type T.
The notation x.(T) is called a type assertion.

Upvotes: 4

Related Questions