Check Exists in 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:     "tivi 1",
			Price:    5,
			Quantity: 9,
			Status:   false,
		},
		entities.Product{
			Id:       "p02",
			Name:     "tivi 2",
			Price:    2,
			Quantity: 8,
			Status:   true,
		},
		entities.Product{
			Id:       "p03",
			Name:     "laptop 3",
			Price:    11,
			Quantity: 7,
			Status:   false,
		},
	}

	var id string = "p02"
	result := isExists(id, products)
	fmt.Println("Result: ", result)
}

func isExists(id string, products []entities.Product) (result bool) {
	result = false
	for _, product := range products {
		if product.Id == id {
			result = true
			break
		}
	}
	return result
}




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

Result:  true