Structures in Go

Grouping together typed data to form records.

syntax

type dragon struct {
    Name string
    Height int
}

Basic struct call example

package main

import (
	"fmt"
)

type dragon struct {
	Name string
	Height int
	
}

func main() {
dragons := dragon{"trex", 10000}
fmt.Println(dragons.Height)

// you can also assign using dot operator
dragon.name = "participants"

}

This shorter declaration form has a few drawbacks that have led the Go community to prefer the longer form in most circumstances. You must provide values for each field in the struct when using the short declaration—you can’t skip fields you don’t care about. This quickly causes short declarations for structs with many fields to become confusing. For this reason, declaring structs using the short form is typically used with structs that have few fields.

The field names in the examples so far have all begun with capital letters. This is more significant than a stylistic preference. The use of capital or lowercase letters for field names affects whether your field names will be accessible to code running in other packages.

Nested struct

Nested struct

We can also use a common struct for other structs too ! Try that.

Note: Always mention name of struct when initializing struct inside struct

struct with Pointer

& is used to get address, * is to extract the value from the address

Return from function

methods on structure

Last updated

Was this helpful?