On Thursday, September 29, 2016 at 8:46:14 PM UTC+8, Konstantin Khomoutov wrote: > > On Thu, 29 Sep 2016 00:25:23 -0700 (PDT) > T L <tapi...@gmail.com <javascript:>> wrote: > > > > > I just want to understand what is the deep reason for the syntax > > > > inconsistency between map index and type assert. > > > > > > a map is fully typed at compile time. even if its key is of type > > > interface{} the language defines how to compare two interface{} > > > values using type assertion here: > > > https://golang.org/ref/spec#Comparison_operators > > > > > > "Interface values are comparable. Two interface values are equal if > > > they have identical dynamic types and equal dynamic values or if > > > both have value nil." > > > > > > Using interface{} in assignments on the other hand is only > > > type-safe at runtime when used with a type assertion. > > > > > > > Aha, it would be more understandable if you can explain it with code. > > :), my English is not very good. > > "One argument lookup" of a map containing values of type interface{} > produces the zero value for type interface{}. That's because as Andrey > said, such map _itself_ is statically typed: the type of its values is > interface{}. > > Conversely, when you type-assert a value of type interface{}, you're > making a claim the _real dynamic run-time_ type of the value held in > that value of type interface{} is such and such. > > Thus even though both operations superficially look the same, they're > doing drastically different things, as Andrey and Dave tried to explain. > > Here's the code: > > package main > > import ( > "fmt" > ) > > func main() { > var zvi interface{} // The zero value for type interface{} > > m := make(map[string]interface{}) > > v := m["abc"] // Returns the zero value for type interface{} > fmt.Println(v == zvi) // Prints "true" > > v = zvi.(int64) // panics beause zvi contains no dynamic type > // information. > } >
I'm still not convinced by your explanation. I never expect the last line should not panic. Type asserting on a nil interface value is expected to panic (it is a surprise that nil map element access doesn't panic). I just expect type asserting on a non-nil interface value shouldn't panic. > > Playground link: https://play.golang.org/p/oS7SWHXgJQ > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.