咨询 golang 接口导入问题

2025 年 8 月 14 日
 chaleaochexist

调用方定义一个接口, 这个接口定义了一个方法, 方法的返回值是一个接口. 因为返回的这个接口本身也是一个抽象类型. 这样设计是否合理?

具体案例可以参考 https://github.com/chaleaoch/golang_demo/tree/master/v5 我得问题也在代码的注释中, 请搜索关键字 "问题"

这个返回接口的方法是: https://github.com/chaleaoch/golang_demo/blob/master/v5/internal/task/a.go#L20

2897 次点击
所在节点    Go 编程语言
15 条回复
3img
2025 年 8 月 14 日
在 Go 里,接口的实现是在 编译期 确定的,而不是像 Python 、JavaScript 那样运行时动态绑定。
sthwrong
2025 年 8 月 14 日
返回值可以是接口类型,主要看你的需求,你如果同时依赖实例的其他方法,返回的接口也要声明该方法。
sthwrong
2025 年 8 月 14 日
直接返回实例,即使接口没有声明该方法,也可以被调用。
sthwrong
2025 年 8 月 14 日
@sthwrong #2 一定要调用的话,可以用断言判断能否转成对应实例,再调用
sthwrong
2025 年 8 月 14 日
cryptovae
2025 年 8 月 14 日
不要为了接口而写接口,接口的本质是归类,将一些 struct 的共同方法抽离出来,如果你本身只有一个 struct 且封装了一个对应的接口,这简直是脱裤子放屁
Curtion
2025 年 8 月 14 日
一般情况下接收接口,返回结构体,相关内容的关键词是: Accept interfaces, return structs ,当然这个观点也有争议,不过可以作为一个切入点看看其它人是怎么想的。
chaleaochexist
2025 年 8 月 14 日
@sthwrong 你是天才! 谢谢.
mcfog
2025 年 8 月 14 日
这个做法本身逻辑、风格等方面都没有问题,但有一个点是为了避免类型耦合,被返回的接口最好是 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.
rainbowhu
2025 年 8 月 14 日
provider 接口和 client 接口共同组成了一套对外的接口,没觉得有啥问题。
chaleaochexist
2025 年 8 月 14 日
@cryptovae 主要是为了单元测试.

@mcfog 哦!!! soga 我试试, 从来没见过还可以这么写. 受教了!!!
spritecn
2025 年 8 月 15 日
@sthwrong 最近看字节的示例好多都是直接不用接口,直接用函数类型 ,然后断言调用,其实蛮好的,很多接口其实只有一个函数
chaleaochexist
2025 年 8 月 15 日
@spritecn 举个例子佬.
mb4555
2025 年 8 月 15 日
@spritecn 那什么要用接口
spritecn
2025 年 8 月 15 日
@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 里随处可见

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

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

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

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

© 2021 V2EX