Golang Custom Type Declaration

In Go, you can create “custom types using type declarations”. A custom type is a user-defined type based on an existing one. You can create custom types to make your code more expressive, readable, and easier to maintain.

To define a custom type declaration in Golang, you can use the “type” keyword.

Example 1

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 defined one slice called apps and then iterated a for loop on the slice.

Example 2

package main

import (

 // Declare a custom type called "MyInt" based on "int"
 type MyInt int

 // Declare a custom type called "Person" based on a struct
 type Person struct {
   Name string
   Age int

func main() {
  // Create a variable of type MyInt
  var num MyInt = 21
  fmt.Println("num is of type MyInt:", num)

  // Create a variable of type Person
  var person Person = Person{"Krunal Lathiya", 30}
  fmt.Println("person is of type Person:", person)


person is of type Person: {Krunal Lathiya 30}

In this code, we created two custom types: MyInt (based on the built-in int type) and Person (based on a struct with Name and Age fields).

In the next step, we created and printed variables of these custom types.

Custom types can also be used with methods, interfaces, and other features of the Go language. However, remember that creating a custom type is considered a different type than the underlying type. Therefore, you’ll need to use explicit conversions to convert between the custom and underlying types.

Leave a Comment

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