Invalid operation: s [k] (type index * S)

I want to define a type like this:

type S map[string]interface{}

and I want to add a method to a type type:

func (s *S) Get( k string) (interface {}){
    return s[k]
}

when the program starts, an error occurred:

invalid operation: s[k] (index of type *S)

So how can I determine the type and add a method to the type?

+5
source share
1 answer

For instance,

package main

import "fmt"

type S map[string]interface{}

func (s *S) Get(k string) interface{} {
    return (*s)[k]
}

func main() {
    s := S{"t": int(42)}
    fmt.Println(s)
    t := s.Get("t")
    fmt.Println(t)
}

Conclusion:

map[t:42]
42

Maps are reference types that contain a pointer to a base map, so you usually don't need to use a pointer for s. I added a method (s S) Putto emphasize this point. For instance,

package main

import "fmt"

type S map[string]interface{}

func (s S) Get(k string) interface{} {
    return s[k]
}

func (s S) Put(k string, v interface{}) {
    s[k] = v
}

func main() {
    s := S{"t": int(42)}
    fmt.Println(s)
    t := s.Get("t")
    fmt.Println(t)
    s.Put("K", "V")
    fmt.Println(s)
}

Conclusion:

map[t:42]
42
map[t:42 K:V]
+10
source

All Articles