Golang type alias and type definitions

There is a keyword type Golang language, type there are two ways, one is the type alias, one is the type definition, is not familiar with the C language (define and typedef) taste?

  • Type Definition
type Student struct {
  name String
  age int
}

type I int
  • Type alias
type Sdt = Student
type I = int

What is the difference between them? Difference is defined as the complete definition of the type of a new type, the type of alias names to take a conventional type alias alias

type I int
type D = int

Take for example the above, I is a new type, and a conventional completely different type int, i.e. type I int type pointer can point to a pointer, and vice versa, similar to the C language typedef. And D int just an alias, and will compile corresponding to pretreatment replaced int, similar to the C language #define.
The above example may be too special, see the following example

type Student struct {
  name String
  age int
}

type Teacher Student

Corresponds to define a new type Teacher, and is equivalent to the following code. Although the two types of memory layout exactly the same, but conceptually, they are two completely different types, can not be compatible with each other.

type Teacher struct {
  name String
  age int
}

This type alias feature is very useful, given the go in some type of writing is very complicated, such as json-related operations, frequently used map [string] interface {} of this type, to write is not very complicated, it does not matter, give it a simple alias! so cool to use up more.

type strMap2Any = map[string]interface {}
Published 158 original articles · won praise 119 · views 810 000 +

Guess you like

Origin blog.csdn.net/u013474436/article/details/103977165