如何在Golang中使用带有地图的接口?

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

How to use interface with map in Golang?

问题

我有一个实现了接口的结构体,因此我可以将该结构体赋值给该接口的变量。

但是我想创建一个类型,将字符串映射到Whoa接口,但在初始化时能够使用具体的结构体。这样做是行不通的,我得到了以下错误信息:

无法在变量声明中使用(map[string]Boom字面量)(类型为map[string]Boom的值)作为poppa值

感谢任何帮助!

package main

type Whoa interface {
	yes()
}

type Boom struct {
	hey string
}

func (b Boom) yes() {

}

type poppa map[string]Whoa

func main() {
	var thisWorks Whoa = Boom{}
	var thisDoesnt poppa = map[string]Boom{}
}
英文:

I have a struct which implements an interface - hence I can assign that struct to a variable of said interface.

But I'd like to create a type which maps from string -> Whoa interface, but to be able to use a concrete struct when initializing. This doesn't work, I'm getting:

cannot use (map[string]Boom literal) (value of type map[string]Boom) as poppa value in variable declaration

Any help appreciated!

package main

type Whoa interface {
	yes()
}

type Boom struct {
	hey string
}

func (b Boom) yes() {

}

type poppa map[string]Whoa

func main() {
	var thisWorks Whoa = Boom{}
	var thisDoesnt poppa = map[string]Boom{}
}

答案1

得分: 3

var thisWorks Whoa = Boom{}

这段代码是有效的因为`Boom{}`实现了`Whoa`接口

你可能会认为既然`Boom`实现了`Whoa`那么`map[string]Boom`也可以是`map[string]Whoa`但实际上不行

你可以创建一个值为`Boom{}``map[string]Whoa`

var thisShould poppa = map[string]Whoa{"first": Boom{}}

这个故事的寓意是*接口类型的切片和映射可以持有满足该接口的任何值但满足接口的类型的切片和映射与该接口的切片和映射并不等价*

> 编写代码将`map[string]Boom{}`复制到`poppa`

如果你有一个想要转换为`map[string]Whoa``map[string]Boom`正确的做法是

whoas := make(map[string]Whoa)
for k, v := range map[string]Boom{} {
  whoas[k] = v
}
英文:
    var thisWorks Whoa = Boom{}

That works because Boom{} implements Whoa.

You might think since Boom implements Whoa, then map[string]Boom can also be a map[string]Whoa. But it cannot.

What you can do is create a map[string]Whoa whose values are Boom{}s.

    var thisShould poppa = map[string]Whoa{"first": Boom{}}

The moral of the story is, slices and maps of interface types may hold any value that satisfies that interface, but slices and maps of types that satisfy an interface are not equivalent to slices and maps of that interface.

> Write code to copy the map[string]Boom{} to a poppa

If you had a map[string]Boom that you wanted to turn into a map[string]Whoa, the right way to do it is something like:

whoas := make(map[string]Whoa)
for k, v := map[string]Boom{} {
  whoas[k] = v
}

huangapple
  • 本文由 发表于 2021年12月9日 03:21:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/70280607.html
匿名

发表评论

匿名网友

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

确定