Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 448
user1820205 Avatar asked Apr 11 '13 02:04

user1820205


1 Answers

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]
like image 87
peterSO Avatar answered Nov 12 '22 09:11

peterSO