How do you declare that a type belongs to a marker interface?

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

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 {
}

我如何声明OrangeLemonFruit,以便在其他地方,一个函数只能返回属于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

}

huangapple
  • 本文由 发表于 2023年6月2日 20:22:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76390107.html
匿名

发表评论

匿名网友

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

确定