Create Object 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) Total() float64 {
	return product.Price * float64(product.Quantity)
}

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,
	}

	fmt.Println("Product 1 Info")
	fmt.Println(product1.ToString())
	fmt.Println("Total: ", product1.Total())

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




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
Total:  45

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