Welcome To Golang By Example

Accessing and Setting Struct Fields in Go (Golang)

Overview

GO struct is named collection of data fields which can be of different types. Struct acts as a container that has different heterogeneous data types which together represents an entity. For example, different attributes are used to represent an employee in an organization. Employee can have

.. and so on. A struct can be used to represent an employee

type employee struct {
    name   string
    age    int
    salary int
}

Accessing and Setting Struct Fields

A struct variable can be created as below

emp := employee{name: "Sam", age: 31, salary: 2000}

Once the struct variable is created, structs fields can be accessed using the dot operator. Below is the format for getting the value

n := emp.name

Similarly a value can be assigned to a struct field too.

emp.name = "some_new_name"

Let’s see an example

package main

import "fmt"

type employee struct {
    name   string
    age    int
    salary int
}

func main() {
    emp := employee{name: "Sam", age: 31, salary: 2000}

    //Accessing a struct field
    n := emp.name
    fmt.Printf("Current name is: %s\n", n)

    //Assigning a new value
    emp.name = "John"
    fmt.Printf("New name is: %s\n", emp.name)
}

Output

Current name is: Sam
New name is: John