1. What is the type alias and type definition?
Type Alias is a new feature added in Go version 1.9. It is mainly used for type compatibility issues in code upgrade, engineering reconstruction, and migration. In the C/C++ language, code reconstruction and upgrading can quickly define new code using macros. In Go, instead of using macros, we choose to use type alias to solve the most complex type name change problem in reconstruction.
The code built-in type definition before Go 1.9 is as follows:
type byte uint8 type rune int32
The code for built-in type definition after Go 1.9 is as follows:
type byte = uint8 type rune = int32
From the above, we can see that this modification is modified with the type alias.
2. Distinguish between type alias and type definitions
Type alias regulations: Type Alias is just an alias for Type. In essence, Type Alias is the same type as Type, that is, the basic data type is the same. For example, the nickname given to us by our family when we were young, and the English name given to us by our English teacher after we went to school, but this name refers to ourselves.
On the surface, there is only one equal sign between type alias and type definition ("="), but in fact, we have a more profound understanding of the differences between the two through a short piece of code, as shown in the following code;
package main import "fmt" // Custom type myInt, the basic type is inttype myInt int //Alias the int typetype intAlias = int func main() { //Declare the a variable as a custom myInt type var a myInt // Output type and default value of a ("a Type: %T, value: %d\n", a, a) //Declare the b variable to type intAlias var b intAlias // Output b type and default value ("b Type: %T, value: %d\n", b, b) }
== Output result ==:
a Type: , value: 0
b Type: int, value: 0
- From the above results we can see that the type of a is , representing the myInt type defined under the main package. A new data type was generated.
- The type of b is int . The intAlias type will only exist in the code, and when the compilation is completed, there will be no intAlias type.
Type definition
Type definition: Declare a new data type based on the primitive type.
// New declaration of a variable c intAlias type var c intAlias c = a ("c Type: %T, value: %d\n", c, c) OutPut Result: cannot use a (type myInt) as type int in assignment
From the above, we can see that the variables a and c are not the same type, so they cannot be assigned directly; they can be modified to c=int(a) through casting.
This is the article about Golang's method of distinguishing type alias and type definitions. For more relevant content on Golang's distinction between type alias and type definitions, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!