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
?
You can't define methods for types in other packages. A code can only define methods for types being in the same package.
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
}
// ...