You can learn more about Type aliasing and the reasoning behind it in the Go proposal page:
https://go.googlesource.com/proposal/+/master/design/16339-alias-decls.md
Type Alias Syntax
Creating a type alias for an existing type is straightforward. An example syntax is as shown:
The syntax above does not create a new name for the existing_type. In essence, the new_name is just another spelling for the existing_type.
Using aliases allows you to introduce a new name for an existing type without breaking the code that references the old name.
To ensure compatibility between the existing type and the alias, the alias should have interchangeable parameter types. The example below shows code with interchangeable types:
import (
"fmt"
"reflect"
)
type foo struct{}
// set new name as bar
type bar = foo
funcmyFunc (i bar) {
fmt.Println(reflect.TypeOf(i))
}
funcmain() {
vari bar
myFunc(i)
}
Both types should convert from an empty interface.
import (
"fmt"
"reflect"
)
type foo struct{}
// set new name as bar
type bar = foo
funcmyFunc (iinterface{}) {
i, ok := i.(bar)
if !ok {
fmt.Println("!bar type")
}
fmt.Println(reflect.TypeOf(i))
}
funcmain() {
vari bar
myFunc(i)
}
Closing
Type aliasing refers to the method of adding a new name to an existing type to improve readability and code refactor. Check the Go docs to learn more.