情况

对于代码库,我使用pion/rtpio包.

我试图通过添加Close()函数来扩展接口RTPwriter.目标是生成一个NewRTPWritCloser()函数,该函数返回具有组合函数的writeCloser.

从软件包中,我看到作者已经创建了界面RTPWriteCloser

type RTPWriteCloser interface {
    RTPWriter
    io.Closer
}

企图

我这样做是为了重用函数,这是错误的,但我还不知道替代方法:


func NewRTPWriteCloser(wc io.WriteCloser) rtpio.RTPWriteCloser {
    writeCloser := rtpio.NewRTPWriter(wc)
    return writeCloser
}

并期望wc有自己的Close()函数就绪,因此返回的writeCloser将满足接口RTPWriteCloser.然而,我得到了(missing method Close)作为一个错误.

函数NewRTPWriter()如下所示:

func NewRTPWriter(w io.Writer) RTPWriter {
    return &RawRTPWriter{
        dst: w,
    }
}

问题

  • 我们如何同时从多个嵌入接口创建一个包含所有所需函数的实例,以满足嵌入接口的要求?
  • 在这个例子中,我们想为RTPWriteCloser接口创建NewRTPWriteCloser个函数,但我们不能先创建一个writer,然后向其添加Close函数?
  • 我必须创建一个RTPWriteCloser的 struct 并重写所有需要的函数吗?(似乎效率低下)

已搜索

例如,我自己搜索了interfaces inside interfacecombining or extending interfaces,但它们并没有让我最终理解我的问题.

推荐答案

您应该定义适配器 struct ,将io.Closer语义添加到基本类型中:

type WrappingRTPWriteCloser struct {
    w RTPWriter
    c io.Closer
}

然后,您应该定义Close方法以满足接口:

func (w *WrappingRTPWriteCloser) Close() error {
    return w.c.Close()
}

然后,您应该在创建实例时创建包装 struct 的新引用:

func NewRTPWriteCloser(wc io.WriteCloser) rtpio.RTPWriteCloser {
    writeCloser := WrappingRTPWriteCloser{
            w: rtpio.NewRTPWriter(wc),
            c: wd,
    }
    return writeCloser
}

另一种解决方案是使用软件包提供的RTPPipe函数,该函数返回RTPReadCloserRTPWriteCloser实例(将RTPReadCloser输入管道连接到RTPWriteCloser输出):

// RTPPipe creates a new RTPPipe and returns the reader and writer.
func RTPPipe() (RTPReadCloser, RTPWriteCloser) {
    r, w := io.Pipe()
    return &pipeRTPReader{closer: r, rtpReader: NewRTPReader(r, 1500)}, &pipeRTPWriter{closer: w, rtpWriter: NewRTPWriter(w)}
}

Go相关问答推荐

Golang regexpp:获取带有右括号的单词

Go 1.22 net/http群组路由

Gorm foreign 密钥

Go PQ驱动程序无法使用默认架构进行查询

使用一元或服务器流将切片从GRPC服务器返回到客户端

是不是有什么原因导致`Strings.EqualFold`不先进行长度比较?

go中跨域自定义验证的问题

如何测试 Zerolog 记录器引发类型错误的日志(log)事件?

使用 goroutine 比较 Golang 中的两棵树是等价的

testcontainers:如何修复绑定源路径不存在

将字符串格式的x509证书生成主题名称

创建新对象后如何返回嵌套实体?

为什么互斥量比 golang 中的通道慢?

整理时转换值

有没有办法判断值是否满足接口中定义的类型约束?

如何通过组合来自不同包的接口来创建接口?

即使一个测试用例失败,如何运行所有测试用例

使用 image/jpeg 编码导致图像饱和/错误像素

为什么 template.ParseFiles() 没有检测到这个错误?

在 Go 中表达函数的更好方法( struct 方法)