In Go, the reserved word type is used to define new types or give a name to an existing type (type alias), whether it is a struct, interface, function, basic type, etc.
It can be used in two main contexts:
1️⃣ Creating a new type based on an existing type
This creates a distinct type, even if it has the same internal representation.
package main
import "fmt"
type Celsius float64
type Fahrenheit float64
func main() {
var c Celsius = 30
var f Fahrenheit = 86
fmt.Println(c, f) // 30 86
// c = f // Error: not the same type
}
✅ Useful to add semantics and type safety.
2️⃣ Defining an alias for an existing type
When using =, the new name does not create a new type, it is just another name for the same type.
package main
import "fmt"
type MyInt = int
func main() {
var x MyInt = 10
var y int = 20
x = y // Works, since MyInt is just an alias
fmt.Println(x)
}
✅ Useful for maintaining compatibility or improving readability without breaking code.
When you do:
type MyInt = int
The = creates an alias — meaning MyInt and int are exactly the same type to the compiler, just with different names. That’s why x = y works.
But if you do:
type MyInt int
Here you are creating a new type, which is based on int but is distinct from int.
In this case, MyInt and int are not directly assignable to each other: