How to do for-range on struct

I embed a map product in the struct products, and how to do for-range loop on the products just like on the product ? here is the code.

package main

type product map[string]bool

func (p product) hasProduct(pro string) bool{
	if _, ok := p[pro]; !ok {
		return false
	}
	return true
}

func (p product) addProduct(pro string) {
	p[pro] = true
}

type products struct {
	number int
	name string
	info string
	product
}

func initProducts() products {
	return products{
		product: make(product, 10),
	}
}

func main() {
	pro := initProducts()
	pro.addProduct("1")
	pro.addProduct("2")
	pro.addProduct("3")
	for _, p := range pro { // range pro.product
		print(p)
	}
}

I hope to use range pro rather than range pro.product, is there any solution ?

2 Likes

You can’t. Either expose the field, or add a getter.

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.