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

huangapple go评论82阅读模式
英文:

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)

那么,我该如何定义这个类型并给它添加方法呢?

英文:

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?

答案1

得分: 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)
}

输出:

map[t:42]
42

映射是引用类型,它们包含对底层映射的指针,因此通常不需要使用指针来操作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)
}

输出:

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

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]

huangapple
  • 本文由 发表于 2013年4月11日 10:32:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/15939734.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定