简体   繁体   中英

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

I want to define a type like this:

type S map[string]interface{}

and I want add a method to the type like this:

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

when the program runs, there was a error like this:

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

So, how do I define the type and add the method to the type?

For example,

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)
}

Output:

map[t:42]
42

Maps are reference types, which contain a pointer to the underlying map, so you normally wouldn't need to use a pointer for s . I've added a (s S) Put method to emphasize the point. For example,

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)
}

Output:

map[t:42]
42
map[t:42 K:V]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM