Methods 无效操作:s[k](类型为*s的索引)

Methods 无效操作:s[k](类型为*s的索引),methods,interface,go,Methods,Interface,Go,我想定义如下类型: type S map[string]interface{} func (s *S) Get( k string) (interface {}){ return s[k] } invalid operation: s[k] (index of type *S) 我想在类型中添加一个方法,如下所示: type S map[string]interface{} func (s *S) Get( k string) (interface {}){ return

我想定义如下类型:

type S map[string]interface{}
func (s *S) Get( k string) (interface {}){
    return s[k]
}
invalid operation: s[k] (index of type *S)
我想在类型中添加一个方法,如下所示:

type S map[string]interface{}
func (s *S) Get( k string) (interface {}){
    return s[k]
}
invalid operation: s[k] (index of type *S)
程序运行时,出现如下错误:

type S map[string]interface{}
func (s *S) Get( k string) (interface {}){
    return s[k]
}
invalid operation: s[k] (index of type *S)
那么,如何定义类型并将方法添加到类型中呢?

例如

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)
}
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)
}
输出:

map[t:42]
42
map[t:42]
42
map[t:42 K:V]
映射是引用类型,其中包含指向基础映射的指针,因此通常不需要为
s
使用指针。我添加了一个
(s)Put
方法来强调这一点。比如说,

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)
}
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)
}
输出:

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

也许可以解释一下指针和值接收器,以及为什么map可以与值接收器一起工作?