如题,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()
}
|  |      1nmap      2021-11-18 17:31:38 +08:00 这是很基础的东西吧 | 
|  |      2youngzy      2021-11-18 17:33:50 +08:00 via Android  1 建议先了解 golang 的 duck type 只要这个 strcut 类型实现了 interface 约束的函数,那么他就可以作为这个 interface 类型返回 | 
|      3freshgoose      2021-11-18 17:35:05 +08:00 面向对象基础知识了,不仅 go 其他语言也是类似的 | 
|  |      4gosidealone OP @youngzy 我可不可以认为这是一种约定? | 
|  |      5kidlj      2021-11-18 17:52:46 +08:00 @gosidealone 这不是一种约定,而是一种抽象。而当你第一次*需要*并实现了这种抽象,你就真正地理解了面向接口编程。 | 
|  |      6BeautifulSoap      2021-11-18 18:31:15 +08:00  1 lz 可以先学学 go 的 interface 的基础 然后 lz 的写法有一点问题,go 推荐 accept interfaces, return structs 。所以别返回接口 | 
|  |      7Nitroethane      2021-11-18 18:44:14 +08:00 via iPhone interface 类型的变量能保存实现了这个 interface 的结构体实例 | 
|  |      8mmrindextt      2021-11-18 19:44:12 +08:00 知识到用时,方觉读书少 | 
|  |      9gosidealone OP | 
|  |      10gosidealone OP @mmrindextt 扎心了 | 
|  |      11gosidealone OP | 
|  |      12xianzhe      2021-11-18 21:05:10 +08:00 via Android 是不是代码不全啊?我看半天也没看出来 HTTP 结构体哪里实现了 Service 接口😭 | 
|  |      13gosidealone OP @xianzhe 是的。我只复制了一部分,但想来我的意思表达明白了 | 
|  |      14nacosboy      2021-11-19 07:18:25 +08:00 via iPhone 结构实现了接口 | 
|      15darknoll      2021-11-19 09:02:51 +08:00 说明 http 实现了这个接口,他是想链式操作吧 | 
|      16thinkingbullet      2021-11-19 09:45:53 +08:00 type HTTP struct {} 肯定在其他的地方实现了 type Service interface {} | 
|  |      17codeMore      2021-11-19 14:21:07 +08:00 因为 HTTP 这个结构体实现了 Start()方法和 Clean()方法,那么其就可以视为一个 Service 接口。 | 
|      18l1203      2021-11-19 17:25:45 +08:00 只要实现了这个接口的类,都可以返回啊。这个就是面向对象里的多态。 | 
|  |      19m16FJ06l0m6I2amP      2021-11-19 19:05:49 +08:00 其实建议写成这样 func NewHTTP() *HTTP { return &HTTP{ outPool: utils.OutPool{}, cfg: HTTPArgs{}, checker: utils.Checker{}, basicAuth: utils.BasicAuth{}, } } |