go - 如何在 Golang 中创建没有字段或方法的顶级对象?

标签 go

由于我来自 Java 并且是 Golang 的新手,所以我将尝试用 Java 解释我想要什么。

    interface Car { }

    class MyCarA implements Car {
      int specificToA
    }

    class MyCarB implements Car {
      int specificToB
    }

我认为这样的接口(interface)(比如Car)在Java中被称为标记接口(interface)。它只是指示编译器进行必要的抽象。

我如何在 Golang 中执行此操作?

我有

type MyCarA struct {
   specificToA int
}
type MyCarB struct {
  specificToB int
}

我现在如何概括这些结构?它应该是一个接口(interface)还是另一个结构?

最佳答案

你可以这样做:

type Car interface { IAmACar() }

type MyCarA struct {
  specificToA int
}
func (MyCarA) IAmACar() {}

type MyCarB struct {
  specificToB int
}
func (MyCarB) IAmACar() {}

您使用 type assertion 测试标记:

_, itIsACar := v.(Car)

playground example

Car 接口(interface)也可用于静态检测错误:

var c Car
c = MyCarA{0} // ok
c = 0 // error, int is not a car

go/ast包做类似的事情。查看函数 exprNode 的用途在文件中 ast.go .

关于go - 如何在 Golang 中创建没有字段或方法的顶级对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44690196/

相关文章:

google-app-engine - GAE Go 测试 - 数据存储查询在测试环境中是否有效?

struct - 如何在 Go 中从结构体创建 []string

go - GKE 无法将卷装载到部署/Pod : timed out waiting for the condition

mongodb - 做一个困难的mongoDB查找

javascript - 在 Javascript 中引用 Go 数组

memory-leaks - 这会导致 Go 中的内存泄漏吗?

go - golang中最灵活的函数签名

mongodb - 创建 session : no reachable servers - mgo

html - 在 go 中提供 .html 模板时,它不会加载任何媒体

json - 对于encoding/json,如何优雅地处理键名称中包含撇号的 API JSON 调用?