interface - Go:工厂返回指针和接口(interface){}类型

标签 interface go factory

考虑以下工厂:Go playground

type TypeA struct {
    placeholder int
}

func NewTypeA() *TypeA {
    return new(TypeA)
}

func main() {
  factory := make(map[string]func() interface{})
  factory["TypeA"] = NewTypeA
}

这给了我以下错误:cannot use NewTypeA (type func() *TypeA) as type func() interface {} in assignment 这很清楚。

我认为 interface{} 可以与指针匹配。

我找到了这个解决方案:Go playground

type Entity interface {}

type TypeA struct {
    Entity
    placeholder int
}

func NewTypeA() Entity {
    return new(TypeA)
}

func main() {
  var tmp interface{}
  factory := make(map[string]func() Entity)
  factory["TypeA"] = NewTypeA
  tmp = factory["TypeA"]()
  log.Println(reflect.TypeOf(tmp))
}

这给了我预期的类型 *TypeA。 有没有其他方法可以直接使用 interface{} 类型而不是“哑”接口(interface) (Entity) 来做到这一点?

最佳答案

我认为您没有完全理解接口(interface){}是什么,因此试图错误地使用它。

this article 中所述:

The interface{} type, the empty interface, is the source of much confusion.

我建议您先阅读那篇文章,然后再看看您正在尝试做什么。

interface{} 不是任何其他类型的占位符,它是 type itself .

因此,如果您创建一个将返回 interface{} 的函数作为键的映射,那么这就是函数需要返回的类型。不是指针或 int 或其他任何东西。

虽然您可以将任何类型的值分配给接口(interface),包括指针类型,但您不能使用其他类型来代替 interface{} 类型。

看来您想要完成的是拥有一个映射,其中包含可以返回任何类型值的函数。您只能通过以不同方式设计您的功能来间接做到这一点。您必须在函数中使用 interface{} 类型,将要返回的值分配给它,然后返回 interface{}。但是您必须返回类型 interface{} 而不是类型 int 或 string 或 *TypeA 或其他任何类型。

关于interface - Go:工厂返回指针和接口(interface){}类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30476861/

相关文章:

postgresql - 创建或更新未在GORM中返回更新后的值

java - 静态工厂方法问题!

c++ - 线性链式工厂和 move 语义

具有多种实现的 Java 通用接口(interface)

bash - 使用 shell 脚本解析 consul 模板文件中的行

import - 是否可以只从包中导入一个函数?

javascript - 通过泛型函数动态修改 TypeScript 类

java - 如果 StringBuilder 无论如何都从 AbstractStringBuilder 继承它,为什么它应该实现 CharSequence 呢?

C# 覆盖 Collection<T> 中的方法

javascript - 防止覆盖提供的内部函数的方法