In Go, a developer can create their own types based on existing ones or declare aliases for code readability and integration with external libraries.
Background:
Go fundamentally simplifies the type system by distinguishing between creating a new type (type MyInt int) and an alias (type MyIntAlias = int). Confusion often arises between them, which affects data compatibility across different parts of the system.
The Problem:
Choosing the wrong way to declare a type can lead to many implicit errors: inability to pass data between packages, incorrect interaction with external libraries, or loss of methods when trying to use an alias.
The Solution:
Code example:
package main import "fmt" type MyInt int // new type func (m MyInt) Double() int { return int(m) * 2 } type MyIntAlias = int // type alias func main() { var a MyInt = 5 var b MyIntAlias = 10 fmt.Println(a.Double()) // works //fmt.Println(b.Double()) // error: method not defined on int }
Key Features:
Can you create an alias for a struct and add methods to it that are different from the base struct?
No. Methods can only be declared for a new type, not for an alias. An alias is just another name for the same type; part of the program does not recognize any "extension" of the type.
type MyStructAlias = SomeStruct // func (s MyStructAlias) NewMethod() {} // Error
Can methods of the base type automatically "stick" to the alias?
Yes, because it is the same type to the compiler. However, you cannot work with new methods: you cannot add unique methods to an alias.
type MyString = string // all methods and functions for string work
What is the difference between type casting and aliasing?
When declaring a new type, explicit casting is required: MyInt(x) where x is an int. For an alias, casting is not needed — the types are completely interchangeable.
type A int type B = int var x int = 3 var a A = A(x) // explicit conversion var b B = x // implicit, the same as int
A developer creates a type alias for an external library, mistakenly thinking they can add their own methods on top of this type and encapsulate transition logic.
Pros:
Cons:
The team creates a new type based on int to represent user IDs, aiming to protect business logic from being mistakenly mixed with other integer values, and adds special methods (validators, converters).
Pros:
Cons: