英文:
How do you declare that a type belongs to a marker interface?
问题
如果我有以下类型:
type Orange struct {
Size float32
}
type Lemon struct {
Color string
}
type Wood struct {
Variety string
}
以及以下接口:
type Fruit interface {
}
我如何声明Orange
和Lemon
是Fruit
,以便在其他地方,一个函数只能返回属于Fruit
类型的东西?(Fruit
是一个标记接口)。
英文:
If I have these types:
type Orange struct {
Size float32
}
type Lemon struct {
Color string
}
type Wood struct {
Variety string
}
And that interface:
type Fruit interface {
}
How do I declare that Orange
and Lemon
are Fruit
,
so that, elsewhere, a function may return only things who are of kind Fruit?
(Fruit
being a marker interface).
答案1
得分: -1
要声明一个类型属于Go中的标记接口,你需要明确声明该类型实现了该接口。在你的情况下,要声明Orange和Lemon类型属于Fruit类型,你可以按照以下方式进行操作:
type Fruit interface {
}
type Orange struct {
Size float32
}
func (o Orange) MethodOfFruit() {
// 如果需要,实现Fruit接口的任何方法
}
type Lemon struct {
Color string
}
func (l Lemon) MethodOfFruit() {
// 如果需要,实现Fruit接口的任何方法
}
英文:
To declare that a type belongs to a marker interface in Go, you need to explicitly state that the type implements the interface. In your case, to declare that Orange and Lemon types are of kind Fruit, you can do the following:
type Fruit interface {
}
type Orange struct {
Size float32
}
func (o Orange) MethodOfFruit() {
// Implement any methods of Fruit interface if required
}
type Lemon struct {
Color string
}
func (l Lemon) MethodOfFruit()
{
// Implement any methods of Fruit interface if required
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论