Declaring Types in Golang

The type operator allows you to define a named type. A named type is based on a pre-existing type. For example:

type num int

In this case, the num type is defined, which is based on the int type. Num represents the int type and will be worked with in the same way as with the int type. However, at the same time, it is a new type.

Define New types

We can define variables of this type and work with them as objects of the base int type:

package main
import "fmt"
 
type num int
 
func main() {     
    var age num = 5
    fmt.Println("the age before ",age)
    age += 10
    fmt.Println("the age after",age)
}

And if we run this will get:

the age before  5
the age after 15

Why do we need a new type?

But the question may arise, why do we need it, why create a new type if it still behaves like an int type? Consider the following situation:

package main
import "fmt"
 
type byte int
type kbyte int
 
func programSize (size byte){
     
    fmt.Println("the program size is:")
    fmt.Println(size, "byte")
}
 
func main() {
     
    var size byte = 4000
    programSize(size)
    var size1 kbyte = 4
    programSize(size1)  // Error Here 
}

The output of this will be an error:

./prog.go:18:17: cannot use size1 (variable of type kbyte) as byte value in argument to programSize

Two named types are defined here: byte and kbyte, which essentially represent the int type and are intended to express the size of a program in byte and kbyte, respectively.
There is also a function (programSize) that displays the size in byte. As a parameter, it takes the value byte namely the value of the byte type, not the int type. This will allow us to reduce the probability of incorrect data being transmitted. That is The transmitted data must be explicitly defined in the program as a value of type byte, not of type int or type kbyte. Thus, with the help of named types, We give the type some extra meaning.

Let's look at another example:

package main

import "fmt"

type tutorials []string

func allTutorials(tuto tutorials) {

	for _, value := range tuto {

		fmt.Println(value)
	}
}

func main() {

	var tutoList tutorials = tutorials{"Docker", "Rust", "TypeScript"}
	allTutorials(tutoList)
}

The result will be:

Docker
Rust
TypeScript

Defined here is a named type called tutorials, which is essentially a slice of strings. This type will represent a kind of tutorial, which includes books in the form of their string titles. You can use the alltutorials function to display the list of the tutorial. At the same time, the allTutorials work with the tutorials type, not with any line slicer.