gpt4 book ai didi

go - 两种不同的类型如何使用接口(interface)在 golang 中实现相同的方法?

转载 作者:IT老高 更新时间:2023-10-28 13:06:21 32 4
gpt4 key购买 nike

假设我有两个结构:

type First struct {
str string
}
type Second struct {
str string
}

并且我希望它们都实现接口(interface) A:

type A interface {
PrintStr() //print First.str or Second.str
}

像这样同时实现 First 和 Second 结构似乎是多余的:

func (f First) PrintStr() {
fmt.Print(f.str)
}

func (s Second) PrintStr() {
fmt.Print(s.str)
}

有没有一种方法可以为所有实现接口(interface) A 的结构提供一个实现?像这样的东西,但它似乎不起作用:

func (a A) PrintStr() {
fmt.Print(a.str)
}

谢谢!

最佳答案

不,你不能,但是你可以创建一个基类型,然后将它嵌入到你的 2 结构中,因此只需要一个基类型的实现:

type WithString struct {
str string
}

type First struct {
WithString
}

type Second struct {
WithString
}

type A interface {
PrintStr() //print First.str or Second.str
}

func (w WithString) PrintStr() {
fmt.Print(w.str)
}

用法:

a := First{
WithString: WithString{
str: "foo",
},
}

Complete Example on Playground

Embed documentation

关于go - 两种不同的类型如何使用接口(interface)在 golang 中实现相同的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31505587/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com