Rabi Siddique
330 words
2 minutes
Structures in Golang
2024-02-12

Go does not have classes, but it provides structures, which are custom data types created using the struct keyword. Structures allow you to group data together. Go also allows you to add methods to these structures. Let’s look at the syntax:

package main

import "fmt"

// Defining the Student structure
type Student struct {
    name     string
    lastName string
    age      int
}

// Method to get the name of the student
func (student Student) getName() string {
    return student.name
}

// Method to get the last name of the student using a pointer receiver
func (student *Student) getLastName() string {
    return student.lastName
}

func main() {
    // Creating an instance of Student
    s := Student{name: "John", lastName: "Doe", age: 21}

    // Calling methods
    fmt.Println("Name:", s.getName())
    fmt.Println("Last Name:", s.getLastName())
}

In the provided code, a structure named Student is defined with the properties name, lastName, and age. Two methods, getName and getLastName, are associated with this structure. These methods can only be called on instances of the Student type.

Method Syntax#

Methods in Go are regular functions with an additional parameter called the receiver. The receiver is used to specify the type to which the method belongs. The receiver type can be almost any type, not just structs. This means you can define methods on basic types like int, bool, string, or even on function types or aliases.

Value Receiver#

  • The getName method uses a value receiver (student Student). This means the method operates on a copy of the Student instance. Changes made inside this method do not affect the original instance.
  • Value receivers are used when you do not need to modify the receiver’s value and the struct is small.

Pointer Receiver#

  • The getLastName method uses a pointer receiver (student *Student). This means the method operates on the original Student instance. Changes made inside this method will affect the original instance.
  • Pointer receivers are preferred when the method needs to modify the receiver’s value or when the struct is large, as it avoids copying the value, making it more efficient.
Structures in Golang
https://rabisiddique.com/posts/structures-in-golang/
Author
Rabi Siddique
Published at
2024-02-12