Reputation: 11
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
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