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

2021-11-18 17:29:06 +08:00
 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()
}
2375 次点击
所在节点    Go 编程语言
19 条回复
nmap
2021-11-18 17:31:38 +08:00
这是很基础的东西吧
youngzy
2021-11-18 17:33:50 +08:00
建议先了解 golang 的 duck type
只要这个 strcut 类型实现了 interface 约束的函数,那么他就可以作为这个 interface 类型返回
freshgoose
2021-11-18 17:35:05 +08:00
面向对象基础知识了,不仅 go 其他语言也是类似的
gosidealone
2021-11-18 17:47:56 +08:00
@youngzy 我可不可以认为这是一种约定?
kidlj
2021-11-18 17:52:46 +08:00
@gosidealone 这不是一种约定,而是一种抽象。而当你第一次*需要*并实现了这种抽象,你就真正地理解了面向接口编程。
BeautifulSoap
2021-11-18 18:31:15 +08:00
lz 可以先学学 go 的 interface 的基础

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

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

https://www.v2ex.com/t/816348

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

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

© 2021 V2EX