英文:
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]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论