Why does golang allow slice type assignment without explicit type conversion?

I thought go does not allow the assignment of a named type to the actual type assignment without explicit type conversion.

But how does it compile without error if I assign []byte in json.RawMessage ?

 var a json.RawMessage // type RawMessage []byte var b []byte a = b var x time.Duration // type Duration int64 var y int64 x = y // ERROR: cannot use y (type int64) as type time.Duration in assignment 

https://play.golang.org/p/oD5LwJl7an

+5
source share
1 answer

int64 is a named type, []byte is an unnamed type.

Named types are indicated by a (possibly qualified) type name; nameless types are specified using a type literal that represents a new type from existing types - golang spec

Besides

Two named types are identical if their type names come from the same TypeSpec. The named and unnamed type are always different. Two unnamed types are identical if the corresponding type literals are identical, that is, if they have the same literal structure and the corresponding components have the same types. - golang spec

therefore

 type MyByteArray []byte type MyInt int var a MyByteArray var b []byte a = b // legal because array is unnamed - their corresponding type literals are identical var x MyInt var y int x = y // illegal because int is named - they don't originate in the same type spec 

Also see Why can I introduce alias functions and use them without casting?

+4
source

Source: https://habr.com/ru/post/1246888/


All Articles