SoFunction
Updated on 2025-03-05

A brief discussion on the use of alias types in go language

What is an alias type

We can declare various custom types with keyword type, similar to:

type People struct {
	name string
	age  int
}

Of course, these types must be within the scope of Go basic and advanced types.

Among them, there is a type called "alias type". We can declare it like this:

type stringAlias = string

This statement states that stringAlias ​​is an alias type of the string type. As the name implies, the difference between an alias type and its source type is probably just in terms of name, they are exactly the same. We can use the following code to test it:

func func10() {
	var s1 stringAlias = "2"
	v, ok := interface{}(s1).(string)
	(ok)
	(v)
	((s1))
}

output:

true
2
string

Judging from the code results, stringAlias ​​and string are actually the same type.

extend

What if we define it like this?

type stringAlias1 string

Or use the above example to test:

func func11() {
	var s1 stringAlias1 = "2"
	v, ok := interface{}(s1).(string)
	(ok)
	(v)
	((s1))
}

output:

false

main.stringAlias1

We can see from the output that stringAlias1 and string are completely two types. This is called the type redefinition.

This is the end of this article about the use of alias types in the go language. For more related go alias types, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!