如何在Golang中创建没有字段或方法的顶级对象? [英] How to create a top level object with no fields or methods in Golang?
问题描述
由于我来自Java并且是Golang的新手,我会尝试在Java中解释我想要的。
Since I am from Java and new to Golang, I will try to explain what I want in Java.
interface Car { }
class MyCarA implements Car {
int specificToA
}
class MyCarB implements Car {
int specificToB
}
我认为这种接口(如Car)在Java中被称为标记接口。这只是表明编译器必要的抽象。
I think such an interface (like Car) is called a marker interface in Java. It is just to indicate the compiler the necessary abstraction.
我如何在Golang中做到这一点?
How can I do this in Golang ?
我有
I have
type MyCarA struct {
specificToA int
}
type MyCarB struct {
specificToB int
}
现在我该如何概括这些结构?它应该是一个接口或其他结构吗?
How can I generalise these structs now ? Should it be an interface or another struct ?
推荐答案
您可以这样做:
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)
Car界面也可用于静态检测错误:
The Car interface can also be used to detect errors statically:
var c Car
c = MyCarA{0} // ok
c = 0 // error, int is not a car
go / ast 包做了类似的事情。请参阅 exprNode < a>在 ast.go 文件中。
The go/ast package does something similar. See uses of the function exprNode in the file ast.go.
这篇关于如何在Golang中创建没有字段或方法的顶级对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!