In our previous tutorial, we have learned the basics of Go Packages, Methods, Variables, Pointers, etc. GoLang doesn’t support class-based programming directly unlike other high-level programming languages like Java, C++, Python, etc.

But in GoLang, we have a way to by which we can achieve similar functionality like class and methods using Structs and associated methods. Though these methods are not defined within the struct rather they’re associated with the struct. We can either let these methods just access data via working as a copy of the struct which is called Value Receivers, or we can actually point through and modify the original struct which is called Pointer Receivers.

Value Receivers are safer to use because it copies the struct into the local scope, which reduces the risk of accidentally modifying the original struct. But Pointer Receivers doesn’t copy the value struct rather it references the original struct through the pointers which give programmer flexibility to directly modify the original struct as per requirements.

In terms of performance, Pointer Receivers are more efficient as they don’t copy the whole struct again into the local scope. thus generating less garbage to cleanup.

We have provided a sample program with comments to explain these 2 concepts.

package main

import "fmt"

// constant to calculate score from points
const score_multiplier float32 = 0.765

/**
 * Define structure for Customer virtual class
 * with the properties like name, email, points, score
 */
type customer struct {
    name string
    email string
    points uint16
    score float32
}

/**
 * This function is a Value Receiver method which take values 
 * from the associated Struct. In this example it's "customer"
 */
func (c customer) get_score() float32 {
    return c.score
}

/**
 * This function is a Pointer Receiver method which take pointer  
 * to the associated Struct and access the values through the pointer.
 * Pointer Receiver is able to update the values directly to the original 
 * Struct as this is a pointer.
 */
func (c *customer) update_score(point uint16) {
    c.points = point
    c.score = float32(point) * score_multiplier
}

func main() {
    fmt.Println("Welcome to Customer Portal Example")

    // Intialize "customer"
    example_customer := customer{
        name: "Foo Bar",
        email: "foo@bar.example",
    }
        
    // now update score based on points
    var point uint16 = 178
    example_customer.update_score(point)
    
    fmt.Println("Score:", example_customer.get_score())
}

Run your GoLang Program: You can simply type “go run filename.go” to run and check as follows:

Program Output