Slice to Map of pointers duplicates values

80 Views Asked by At

This is a beginner question about why I get such a result when trying to obtain a Map from a Slice in go lang. I have this code:

func (p *ProductsStruct) ToMap() map[int32]*Product {
    result := map[int32]*Product{}

    for _, prod := range p.Products {
        result[prod.ProductId] = &prod
    }

    return result
}

ProductsStruct has just a slice of Product and Product struct is as follows

type ProductsMedusa struct {
    Products []ProductMedusa
}

type Product struct {
    ProductId    int32
    ProductTitle string
    PriceUSD     float32
}

I cannot understand why calling the function ToMap() produces a result with all the keys but pointers to same object: the last. Also, I am aware of the fact that if I don't use map values as pointers, it works fine.

enter image description here

Thanks

0

There are 0 best solutions below