dongping6974 2014-01-22 07:30
浏览 19

接口{}类型的理解

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?

  • 写回答

1条回答 默认 最新

  • duanping1920 2014-01-22 07:35
    关注

    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.

    评论

报告相同问题?