Go 问题请教,一个函数返回值为接口类型却返回结构体,这是为什么?

2021 年 11 月 18 日
 gosidealone

如题,NewHTTP()函数返回值是一个接口,但是 return 的是一个结构体,凭什么啊?为什么这么做啊?返回值改成*HTTP 有什么区别嘛?求教

type HTTP struct {
	outPool   utils.OutPool
	cfg       HTTPArgs
	checker   utils.Checker
	basicAuth utils.BasicAuth
}

func NewHTTP() Service {
	return &HTTP{
		outPool:   utils.OutPool{},
		cfg:       HTTPArgs{},
		checker:   utils.Checker{},
		basicAuth: utils.BasicAuth{},
	}
}

type Service interface {
	Start(args interface{}) (err error)
	Clean()
}
3171 次点击
所在节点    Go 编程语言
19 条回复
nmap
2021 年 11 月 18 日
这是很基础的东西吧
youngzy
2021 年 11 月 18 日
建议先了解 golang 的 duck type
只要这个 strcut 类型实现了 interface 约束的函数,那么他就可以作为这个 interface 类型返回
freshgoose
2021 年 11 月 18 日
面向对象基础知识了,不仅 go 其他语言也是类似的
gosidealone
2021 年 11 月 18 日
@youngzy 我可不可以认为这是一种约定?
kidlj
2021 年 11 月 18 日
@gosidealone 这不是一种约定,而是一种抽象。而当你第一次*需要*并实现了这种抽象,你就真正地理解了面向接口编程。
BeautifulSoap
2021 年 11 月 18 日
lz 可以先学学 go 的 interface 的基础

然后 lz 的写法有一点问题,go 推荐 accept interfaces, return structs 。所以别返回接口
Nitroethane
2021 年 11 月 18 日
interface 类型的变量能保存实现了这个 interface 的结构体实例
mmrindextt
2021 年 11 月 18 日
知识到用时,方觉读书少
gosidealone
2021 年 11 月 18 日
@BeautifulSoap
@Nitroethane 谢谢大佬们指点,大概明白了 确实基础不牢固
gosidealone
2021 年 11 月 18 日
@mmrindextt 扎心了
gosidealone
2021 年 11 月 18 日
@nmap
@freshgoose 新手理解下 哈哈
xianzhe
2021 年 11 月 18 日
是不是代码不全啊?我看半天也没看出来 HTTP 结构体哪里实现了 Service 接口😭
gosidealone
2021 年 11 月 18 日
@xianzhe 是的。我只复制了一部分,但想来我的意思表达明白了
nacosboy
2021 年 11 月 19 日
结构实现了接口
darknoll
2021 年 11 月 19 日
说明 http 实现了这个接口,他是想链式操作吧
thinkingbullet
2021 年 11 月 19 日
type HTTP struct {} 肯定在其他的地方实现了 type Service interface {}
codeMore
2021 年 11 月 19 日
因为 HTTP 这个结构体实现了 Start()方法和 Clean()方法,那么其就可以视为一个 Service 接口。
l1203
2021 年 11 月 19 日
只要实现了这个接口的类,都可以返回啊。这个就是面向对象里的多态。
m16FJ06l0m6I2amP
2021 年 11 月 19 日
其实建议写成这样
func NewHTTP() *HTTP {
return &HTTP{
outPool: utils.OutPool{},
cfg: HTTPArgs{},
checker: utils.Checker{},
basicAuth: utils.BasicAuth{},
}
}

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://study.congcong.us/t/816348

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX