When to create/use "type" instead of "var"

Hello folks,

I am learning golang and also fairly new to programming.
I wanted to understand the “why” and “when” for my question.

In a tutorial I saw the below code…

var a int // creates a variable named a
type a int // creates a int type named a

I have noticed similar patterns in multiple places. When do we need to create variable vs type?

Thanks in advance.

A variable can hold a value of a given type.

Types describe how a value is allowed to look like.

1 Like

Usually you define a type like above when you want to make sure that integers (in this case) used for different purposes cannot be mixed up accidentally.

2 Likes

Just adding to the answers here: you might describe a type to give extra meaning to a more primitive type. For example, in the stdlib byte is just an alias for uint8 - but byte holds a different meaning to developers. Here’s a real-world scenario I deal with all the time, where I might have different cloud providers. Declare a type for my providers (or whatever):

// Block storage providers
type BlockStorageProvider uint8

// Block storage provider options
const (
	AWS BlockStorageProvider = iota
	GoogleCloud
	Azure
)

… which makes the intended use in this function much more obvious:

func doSomething(provider BlockStorageProvider) {
	// In reality this might return a client or do something
	switch provider {
	case AWS:
		fmt.Println("Doing something with AWS")
	case GoogleCloud:
		fmt.Println("Doing something with Google Cloud")
	case Azure:
		fmt.Println("Doing something with Azure")
	default:
		fmt.Println("Unknown provider:", provider)
	}
}

I COULD just pass in a uint8 there with a note to look in the constants for the options, but by declaring a type I’m giving uint8 extra meaning. Just like byte means something different in my mind than uint8 even though they’re the same thing. Take a look at the go source for more examples of this:

https://cs.opensource.google/go/go/+/refs/tags/go1.19.1:src/go/types/basic.go;l=43

As you can see, byte is of type BasicKind which is just an int for example:

// BasicKind describes the kind of basic type.
type BasicKind int
2 Likes