Pointer Receivers in Object Oriented Programming in Golang

Create new folder named entities. In entities folder, create new file named product.go as below:

package entities

import "fmt"

type Product struct {
	Id       string
	Name     string
	Price    float64
	Quantity int
	Status   bool
}

func NewProduct(id string, name string, price float64, quantity int, status bool) Product {
	product := Product{id, name, price, quantity, status}
	return product
}

func (product Product) ToString() string {
	return fmt.Sprintf("id: %s\nname: %s\nprice: %0.2f\nquantity: %d\nstatus: %t", product.Id, product.Name, product.Price, product.Quantity, product.Status)
}

func (product Product) ChangeValue1(name string) {
	product.Name = name
}

func (product *Product) ChangeValue2(name string) {
	product.Name = name
}




Create new folder named src. In src folder, create new file named main.go as below:

package main

import (
	"entities"
	"fmt"
)

func main() {
	product1 := entities.Product{
		Id:       "p01",
		Name:     "tivi 1",
		Price:    5,
		Quantity: 9,
		Status:   false,
	}

	product1.ChangeValue1("abc")
	fmt.Println("Product 1 Info")
	fmt.Println(product1.ToString())

	product2 := entities.NewProduct("p02", "name 2", 2, 7, true)
	product2.ChangeValue2("def")
	fmt.Println("Product 2 Info")
	fmt.Println(product2.ToString())
}

Open Terminal windows in Visual Studio Code and run command line: go run main.go

Product 1 Info
id: p01
name: tivi 1
price: 5.00
quantity: 9
status: false

Product 2 Info
id: p02
name: def
price: 2.00
quantity: 7
status: true