How to do for-range on struct


(Luoheng) #1

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 ?


(Norbert Melzer) #2

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