Welcome To Golang By Example

Menu
  • Home
  • Blog
  • Contact Us
  • Support this website
Menu

Accessing and Setting Struct Fields in Go (Golang)

Posted on June 14, 2020June 14, 2020 by admin

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

  • Name of string type
  • Age of int type
  • DOB of time.Time type
  • Salary of int type

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

type employee struct {
    name   string
    age    int
    salary int
}

Table of Contents

  • Accessing and Setting Struct Fields

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
  • go
  • golang
  • Follow @golangbyexample

    Popular Articles

    Golang Comprehensive Tutorial Series

    All Design Patterns in Go (Golang)

    Slice in golang

    Variables in Go (Golang) – Complete Guide

    OOP: Inheritance in GOLANG complete guide

    Using Context Package in GO (Golang) – Complete Guide

    All data types in Golang with examples

    Understanding time and date in Go (Golang) – Complete Guide

    ©2025 Welcome To Golang By Example | Design: Newspaperly WordPress Theme