dongzanxun2790 2016-07-18 11:04
浏览 57
已采纳

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

consider this working sample code, which extends (not exactly) the

type multiWriter struct {
    writers []Writer
}

from io package, to add just two methods named Remove and Append to manipulate internal 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)
}

is there any concise way to do this, to add just two methods named Remove and Append to io.MultiWriter?

  • 写回答

1条回答 默认 最新

  • 普通网友 2016-07-18 11:24
    关注

    You can't define methods for types in other packages. A code can only define methods for types being in the same package.

    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.

    So there is no other way to extend the unexported type io.multiWriter with methods other than copy its full code and add the methods to your own type.

    Note: As an implementation note, in your multiWriter.Remove() method once you find the removable writer, after reslicing you can "break" (from the inner loop) to omit the rest of the slice:

    // ...
    if t.writers[i] == v {
        t.writers = append(t.writers[:i], t.writers[i+1:]...)
        break
    }
    // ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)