调用方定义一个接口, 这个接口定义了一个方法, 方法的返回值是一个接口. 因为返回的这个接口本身也是一个抽象类型. 这样设计是否合理?
具体案例可以参考 https://github.com/chaleaoch/golang_demo/tree/master/v5 我得问题也在代码的注释中, 请搜索关键字 "问题"
这个返回接口的方法是: https://github.com/chaleaoch/golang_demo/blob/master/v5/internal/task/a.go#L20
![]() |
1
3img 20 天前
在 Go 里,接口的实现是在 编译期 确定的,而不是像 Python 、JavaScript 那样运行时动态绑定。
|
2
sthwrong 20 天前
返回值可以是接口类型,主要看你的需求,你如果同时依赖实例的其他方法,返回的接口也要声明该方法。
|
3
sthwrong 20 天前
直接返回实例,即使接口没有声明该方法,也可以被调用。
|
6
cryptovae 20 天前
不要为了接口而写接口,接口的本质是归类,将一些 struct 的共同方法抽离出来,如果你本身只有一个 struct 且封装了一个对应的接口,这简直是脱裤子放屁
|
![]() |
7
Curtion 20 天前
一般情况下接收接口,返回结构体,相关内容的关键词是: Accept interfaces, return structs ,当然这个观点也有争议,不过可以作为一个切入点看看其它人是怎么想的。
|
![]() |
8
chaleaochexist OP @sthwrong 你是天才! 谢谢.
|
![]() |
9
mcfog 20 天前
这个做法本身逻辑、风格等方面都没有问题,但有一个点是为了避免类型耦合,被返回的接口最好是 alias of unnamed type
以 OP 代码为例,本来没有耦合的结构因为 SSHClient 是 named type ,导致实现方需要依赖调用方(的类型)才能实现接口,白费了这一层抽象。修改方法是 - type SSHClient interface { + type SSHClient = interface { 然后这个 type 在实现侧拷贝一份。Golang 格言:A little copying is better than a little dependency. |
![]() |
10
rainbowhu 20 天前
provider 接口和 client 接口共同组成了一套对外的接口,没觉得有啥问题。
|
![]() |
11
chaleaochexist OP |
![]() |
13
chaleaochexist OP @spritecn 举个例子佬.
|
15
spritecn 19 天前 ![]() @chaleaochexist
// Copyright 2022 CloudWeGo Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package netpoll import ( "net" "time" ) // CloseCallback will be called after the connection is closed. // Return: error is unused which will be ignored directly. type CloseCallback func(connection Connection) error --- netpoll 里随处可见 |