Good day! I am new to Go and I have a problem. There is a code:

package main import ( "fmt" ) type MyMap map[int]struct{} func (iw *MyMap) Add(item int) { *iw[item] = struct{}{} } func main() { iw := make(map[int]struct{}) iw.Add(1) iw.Add(2) iw.Add(3) iw.Add(2) fmt.Println(iw) } 

When starting it gives an error:

 invalid operation: iw[item] (type *MyMap does not support indexing) 

How to make this method work without casting ala types:

 func (iw *MyMap) Add(item int) { t := map[int]struct{}(*iw) t[item] = struct{}{} *iw = MyMap(t) } 

Thank!

    1 answer 1

    The priority of dereferencing the least, it is necessary to put brackets.

     func (iw *MyMap) Add(item int) { //vv Вот тут вот (*iw)[item] = struct{}{} } 

    In general, map is a reference type, you don’t need to do methods with pointers, hence the problem began to grow =)

     package main import ( "fmt" ) type MyMap map[int]struct{} func (iw MyMap) Add(item int) { iw[item] = struct{}{} } func main() { iw := make(MyMap) iw.Add(1) iw.Add(2) iw.Add(3) iw.Add(2) fmt.Println(iw) }