Golang Custom Type Declaration: The Complete Guide

Go is not Object Oriented Programming language like Java, PHP, or Python. It has a unique design pattern. In this tutorial, we will see an approach to defining our custom types in Golang.

Golang Custom Type Declaration

To define a custom type declaration in Golang, use the type keyword. Let’s create a new file inside your folder called hello.go and add the following code.

/* hello.go */

package main

import "fmt"

func main() {
   apps := []string{"Facebook", "Instagram", "WhatsApp"}

   for i, app := range apps {
	fmt.Println(i, app)
   }
}

The output of the above code is the following.

Go Custom Type Declarations Tutorial

So, we have defined one slice called apps and then iterated a for loop on the slice.

Now, here, we can define the type app.

Okay, so create a new file in the same app folder.go and add the following code.

/* app.go */

package main

type app []string

So, in this file, we have defined a type app.

Now, we can use this type inside the hello.go file.

Also, we can define a receiver’s function inside the app.go file. See the following code.

/* app.go */

package main

import "fmt"

type app []string

func (a app) print() {
   for i, app := range a {
	 fmt.Println(i, app)
   }
}

In the above code, the receiver’s function is print(), which we can use directly inside the hello.go file, and it will print all the apps.

Here, we have defined the same for loop, which we have defined in the hello.go file earlier.

So, now we do not need to write this code on hello.go. So, our final hello.go code is the following.

/* hello.go */

package main

func main() {
   apps := app{"Facebook", "Instagram", "WhatsApp"}
   apps.print()
}

Here, inside the func main(), see the first line. We have defined the type app.

We do not need to import the app.go file in this file; it will take directly. Then, finally, we need to run both files simultaneously, and we are good to go.

Also, we have called the receiver’s function defined inside the app.go file will print all the apps.

Now, run the following command in the terminal.

go run hello.go app.go

See the below output.

Go Custom Type Declarations Tutorial With Example

This is how we can define and use our types in another file.

That’s it for this tutorial.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.