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

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

func main() {
	pro := initProducts()
	for _, p := range pro { // range pro.product

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.