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

use*_*205 5 methods interface go

我想定义一个这样的类型:

type S map[string]interface{}
Run Code Online (Sandbox Code Playgroud)

我想在这个类型中添加一个方法:

func (s *S) Get( k string) (interface {}){
    return s[k]
}
Run Code Online (Sandbox Code Playgroud)

当程序运行时,出现如下错误:

invalid operation: s[k] (index of type *S)
Run Code Online (Sandbox Code Playgroud)

那么,如何定义类型并将方法添加到类型中?

pet*_*rSO 10

例如,

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)
}
Run Code Online (Sandbox Code Playgroud)

输出:

map[t:42]
42
Run Code Online (Sandbox Code Playgroud)

映射是引用类型,它包含指向底层映射的指针,因此通常不需要使用指针s.我添加了一种(s S) Put方法来强调这一点.例如,

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)
}
Run Code Online (Sandbox Code Playgroud)

输出:

map[t:42]
42
map[t:42 K:V]
Run Code Online (Sandbox Code Playgroud)

  • 可能会在指针与值接收器上进行一些说明,以及为什么map可以与值接收器一起工作? (3认同)