Background:
The introduction of type aliases in Go is related to the need to ensure a smoother transition between API versions when a type moves from one package to another. Prior to Go 1.9, only new type declarations were used, but now type aliases are supported.
Problem:
Many confuse alias and new type — mistakenly consider them identical, which leads to errors during conversions, methods, and interface passing.
Solution:
Type alias creates an alternative name for an existing type, while declaring a new type is creating a new unique type based on an existing one. Aliases allow for maintaining backward compatibility and integrating old and new types without conversion.
Code example:
// New type type MyString string // Type alias type MyStringAlias = string
Key features:
Can you add methods to a type through alias?
No, methods can only be added to new types, and the alias is not a new type, but the same as the original Type.
type Alias = int // func (a Alias) Method() {} // error!
What is the difference in comparing alias types and new types?
Alias is comparable to the base type and takes its value without conversion. New type is incompatible even if based on the same type.
type T1 = int var a T1 = 10 // ok var b int = a // ok type T2 int var c T2 = 10 // var d int = c // compilation error
When is alias better than new type?
When re-exporting a type between packages or ensuring transparent API migration without recompiling client code. For example:
type OldType = NewType // alias is more convenient for maintaining old API versions
In the project, a type is renamed using a new type instead of an alias, which breaks compatibility
type OldType int
Pros:
Cons:
Type alias is used for transparent API migration
type OldType = NewType
Pros:
Cons: