25.Creating Your Own Type - Programming in GO

Posted on Mar 14, 2019   ∣  1 min read  ∣  GO

Creating Your Own Type

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.

package main

import (
	"fmt"
)

var a int
type hotdog int
var b hotdog

func main() {
	a = 42
	b = 43
	fmt.Println(a)
	fmt.Printf("%T\n", a)
	fmt.Println(b)
	fmt.Printf("%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.

package main

import (
	"fmt"
)

var a int
type hotdog int
var b hotdog

func main() {
	a = 42
	b = a  // we cannot assign the value of a type int to a type hotdog
	fmt.Println(a)
	fmt.Printf("%T\n", a)
	fmt.Println(b)
	fmt.Printf("%T\n", b)
}

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