Initialize Slice of Structures in Golang

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

package entities

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

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

package main

import (
	"entities"
	"fmt"
)

func main() {
	var products = []entities.Product{
		entities.Product{
			Id:       "p01",
			Name:     "name 1",
			Price:    5,
			Quantity: 9,
			Status:   false,
		},
		entities.Product{
			Id:       "p02",
			Name:     "name 2",
			Price:    2,
			Quantity: 8,
			Status:   true,
		},
		entities.Product{
			Id:       "p03",
			Name:     "name 3",
			Price:    11,
			Quantity: 7,
			Status:   false,
		},
	}
	fmt.Println("Product List")
	Display1(products)
	fmt.Println("Product List")
	Display2(products)
}

func Display1(products []entities.Product) {
	for i := 0; i < len(products); i++ {
		fmt.Println("Id: ", products[i].Id)
		fmt.Println("Name: ", products[i].Name)
		fmt.Println("Price: ", products[i].Price)
		fmt.Println("Quantity: ", products[i].Quantity)
		fmt.Println("Status: ", products[i].Status)
		fmt.Println("Sub Total: ", products[i].Price*float64(products[i].Quantity))
		fmt.Println("==========================")
	}
}

func Display2(products []entities.Product) {
	for _, product := range products {
		fmt.Println("Id: ", product.Id)
		fmt.Println("Name: ", product.Name)
		fmt.Println("Price: ", product.Price)
		fmt.Println("Quantity: ", product.Quantity)
		fmt.Println("Status: ", product.Status)
		fmt.Println("Sub Total: ", product.Price*float64(product.Quantity))
		fmt.Println("==========================")
	}
}




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

Product List
Id:  p01
Name:  name 1
Price:  5
Quantity:  9
Status:  false
Sub Total:  45
==========================
Id:  p02
Name:  name 2
Price:  2
Quantity:  8
Status:  true
Sub Total:  16
==========================
Id:  p03
Name:  name 3
Price:  11
Quantity:  7
Status:  false
Sub Total:  77
==========================

Product List
Id:  p01
Name:  name 1
Price:  5
Quantity:  9
Status:  false
Sub Total:  45
==========================
Id:  p02
Name:  name 2
Price:  2
Quantity:  8
Status:  true
Sub Total:  16
==========================
Id:  p03
Name:  name 3
Price:  11
Quantity:  7
Status:  false
Sub Total:  77
==========================