Structs in Go

· 257 words · 2 minute read

Struct in Go allows to create custom data types. In the example below User is a struct type, it’s defined using the type keyword followed by the struct name and then struct. Struct can have once or more fields in it and fields are defined using name and type.

For example:

package main

import "fmt"

func main() {
	type User struct {
		firstname, lastname string
		age                 int
	}

	u1 := User{
		firstname: "Gagandeep",
		lastname:  "Singh",
		age:       32}
	fmt.Println(u1.firstname, u1.lastname, u1.age)
}

Output -> Gagandeep Singh 32

We can create a variable using the custom struct (u1 in the above example) and provide the values. If value for any of the field is not provided, then it will default to zero value.

Another short way of defining value is without using the field names as below. Be sure to order the values and type similar to defined in the struct type.

  u1 := User{
      "Gagandeep",
      "Singh",
      32}

The field defined in the struct value can be accessed via [variable name][.][field name] dot operator. For example

  fmt.Println(u1.firstname, u1.lastname, u1.age)

Comparing Struct values

Two struct values are only equal if all their fields are equal. Even if one of the field value doesn’t match, the comparison will return false.

func main() {
	type User struct {
		firstname, lastname string
		age                 int
	}

	u1 := User{
		firstname: "Gagandeep",
		lastname:  "Singh",
		age:       32}

    u2 := User{
		firstname: "Gagandeep",
		lastname:  "Singh",
		age:       32}

    u3 := User{
		firstname: "Gagandeep",
		lastname:  "Singh",
		age:       33}

	fmt.Println(u1 == u2)
	fmt.Println(u1 == u3)
}

Output ->
true
false
Go