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: Defining custom type in Go

package main

import "fmt"

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

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

Output

Go Custom Type Declarations Tutorial

Example 2

package main

import (
  "fmt"
)

 // 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)
}

Output

person is of type Person: {Krunal Lathiya 30}

That’s it!

Leave a Comment

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