AppDividend
Latest Code Tutorials

Go Custom Type Declarations Tutorial With Example

0

Go Custom Type Declarations Tutorial With Example is today’s topic. 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 in which we will define our custom types in Go.

Go Custom Type Declarations Tutorial

We can define our own types in Go. 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 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 folder called app.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. Our final hello.go code is 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. We need to run both files at the same time, and we are good to go.

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

Now, run the following command in the terminal.

go run hello.go app.go

The output is following.

 

Go Custom Type Declarations Tutorial With Example

See this is how we can define our own types and use them in another file.

Finally, Go Custom Type Declarations Tutorial With Example is over.

Leave A Reply

Your email address will not be published.

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