Creating Your Own Type

Part of Golang Mastery course

~15 min read
Interactive
Hands-on
Beginner-friendly

Some people say, "Go is all about 'type.'" Go is a static programming language, and at the heart of a static programming language is that once you declare that a variable is of a certain type, that's static; it doesn't change.

Let's try creating our own type in the Go playground.

example.go
package main
 
import (
string">"fmt"
)
 
var a int
type hotdog int
var b hotdog
 
func main() {
a = 42
b = 43
fmt.Println(a)
fmt.Printf(string">"%T\n", a)
fmt.Println(b)
fmt.Printf(string">"%T\n", b)
}
 

This returns:

42 int 43 main.hotdog

So we can see that the value of a is 42 and it is of type int, and the value of b is 43 and it is of type hotdog from the package main.

We created a type hotdog with the line type hotdog int, we declared a variable of type hotdog with var b hotdog, we assigned a value to the variable with b = 43

Go is a static programming language, so if I want to now do something like assign the value of b to a, with a = b the compiler will complain. We cannot take the value of something of type hotdog and assign it to something that is of type int.

example.go
package main
 
import (
string">"fmt"
)
 
var a int
type hotdog int
var b hotdog
 
func main() {
a = 42
b = a string">"comment">// we cannot assign the value of a type int to a type hotdog
fmt.Println(a)
fmt.Printf(string">"%T\n", a)
fmt.Println(b)
fmt.Printf(string">"%T\n", b)
}
 

returns tmp/sandbox982815840/main.go:13: cannot use a (type int) as type hotdog in assignment

Your Progress

32 of 103 modules
31%
Started31% Complete
Previous
SpaceComplete
Next