gpt4 book ai didi

go - 如何扩展标准 Golang 未导出的结构类型?

转载 作者:IT王子 更新时间:2023-10-29 01:42:04 25 4
gpt4 key购买 nike

考虑这个工作示例代码,它扩展(不完全)

type multiWriter struct {
writers []Writer
}

io 包中,添加名为 RemoveAppend 的两个方法来操作内部 slice writers:

package main

import (
"io"
"os"
)

func main() {
w1, e := os.Create("file1.txt")
if e != nil {
panic(e)
}
w2, e := os.Create("file2.txt")
if e != nil {
panic(e)
}
mw := MultiWriter(w1, w2)
data := []byte("Hello ")
_, e = mw.Write(data)
if e != nil {
panic(e)
}

var m *multiWriter = mw.(*multiWriter)
m.Remove(w2)
w2.Close()
w3, e := os.Create("file3.txt")
if e != nil {
panic(e)
}
m.Append(w3)
data = []byte("World ")
_, e = mw.Write(data)
if e != nil {
panic(e)
}
w3.Close()
w1.Close()
}
func (t *multiWriter) Remove(writers ...io.Writer) {
for i := len(t.writers) - 1; i > 0; i-- {
for _, v := range writers {
if t.writers[i] == v {
t.writers = append(t.writers[:i], t.writers[i+1:]...)
break
}
}
}
}
func (t *multiWriter) Append(writers ...io.Writer) {
t.writers = append(t.writers, writers...)
}

type multiWriter struct {
writers []io.Writer
}

func (t *multiWriter) Write(p []byte) (n int, err error) {
for _, w := range t.writers {
n, err = w.Write(p)
if err != nil {
return
}
if n != len(p) {
err = io.ErrShortWrite
return
}
}
return len(p), nil
}

var _ stringWriter = (*multiWriter)(nil)

func (t *multiWriter) WriteString(s string) (n int, err error) {
var p []byte // lazily initialized if/when needed
for _, w := range t.writers {
if sw, ok := w.(stringWriter); ok {
n, err = sw.WriteString(s)
} else {
if p == nil {
p = []byte(s)
}
n, err = w.Write(p)
}
if err != nil {
return
}
if n != len(s) {
err = io.ErrShortWrite
return
}
}
return len(s), nil
}

// MultiWriter creates a writer that duplicates its writes to all the
// provided writers, similar to the Unix tee(1) command.
func MultiWriter(writers ...io.Writer) io.Writer {
w := make([]io.Writer, len(writers))
copy(w, writers)
return &multiWriter{w}
}

// stringWriter is the interface that wraps the WriteString method.
type stringWriter interface {
WriteString(s string) (n int, err error)
}

有什么简洁的方法可以做到这一点,只添加名为 RemoveAppend 的两个方法到 io.MultiWriter

最佳答案

您不能为其他包中的类型定义方法。代码只能为同一包中的类型定义方法。

Spec: Method declarations:

The type denoted by T is called the receiver base type; it must not be a pointer or interface type and it must be declared in the same package as the method.

因此除了复制其完整代码并将方法添加到您自己的类型之外,没有其他方法可以使用方法扩展未导出的类型 io.multiWriter

注意:作为实现说明,在您的multiWriter.Remove() 方法中,一旦您找到可移动写入器,在重新 slice 后您可以“中断”(从内部loop) 以省略 slice 的其余部分:

// ...
if t.writers[i] == v {
t.writers = append(t.writers[:i], t.writers[i+1:]...)
break
}
// ...

关于go - 如何扩展标准 Golang 未导出的结构类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38435091/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com