Go条件指针值

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

Go conditional pointer value

问题

我在程序中有几个结构体。我有一个指针,应该根据条件指向其中一个结构体。这是一个简短的非功能示例:

  1. type Struct1 struct {
  2. name string
  3. }
  4. type Struct2 struct {
  5. name string
  6. }
  7. func main() {
  8. var outputDevice
  9. switch inputValue {
  10. case "one":
  11. outputDevice = &Struct1{name: "name"}
  12. case "two":
  13. outputDevice = &struct2{name: "name"}
  14. }
  15. }

请注意,这两个结构体都有一个共同的接口:

  1. type Output interface {
  2. Print() error
  3. }

有关如何解决这个问题的任何想法吗?

英文:

I have a couple of structs in a program. I have a pointer that should conditionally point to one of these structs. Here is a short non-functioning example:

  1. type Struct1 struct {
  2. name string
  3. }
  4. type Struct2 struct {
  5. name string
  6. }
  7. func main() {
  8. var outputDevice
  9. switch inputValue {
  10. case "one":
  11. outputDevice = &Struct1{name: "name"}
  12. case "two":
  13. outputDevice = &struct2{name: "name"}
  14. }
  15. }

Note, both of the structs have a common interface:

  1. type Output interface {
  2. Print() error
  3. }

Any ideas about how to tackle this problem.

答案1

得分: 1

这正是接口的用途。

如果你的两种类型已经共享一个公共接口,那么将你的变量声明为接口类型:

  1. var outputDevice Output
英文:

This is exactly what interfaces are for.

If your two types already share a common interface, than make your variable of the interface type:

  1. var outputDevice Output

huangapple
  • 本文由 发表于 2022年3月8日 06:54:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/71388176.html
匿名

发表评论

匿名网友

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

确定