type myInt int32
type myInt = int32
Not the same concept as
-
Custom type:
type myInt int32
A type defined in this way is an entirely new type that
int32
has the same underlying structure as but isint32
not compatible with the type.type myInt int32
var a int32 = 5 var b myInt = a // 这里会产生编译错误
Although
myInt
the underlying types of areint32
, they are distinct in the type system. -
Type aliases:
type myInt = int32
Type aliasing is to give an existing type a new name that is exactly the same as the original type in the type system.
type myInt = int32
var a int32 = 5 var b myInt = a // 这里不会产生编译错误
Here
myInt
isint32
an alias for , so no compile errors will be generated. -
Summarize
-
A custom type creates an entirely new type that is incompatible with the original type in the type system.
-
A type alias simply gives an existing type a new name that is exactly the same as the original type in the type system.
-
Custom types can be used for encapsulation or abstraction, and type aliases can be used to ensure backward compatibility or to simplify type names.
By understanding these differences, you can use Go's type system more flexibly to meet various programming needs.
-