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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With