2 回答
TA贡献1875条经验 获得超5个赞
您的代码中有一个错字,但无论如何都没有必要将 func 包装到结构中。相反,您可以只定义一个包装函数的 WriteFunc 类型,并且您可以在其上定义一个 Write 方法。这是一个完整的例子。
package main
import (
"fmt"
"io"
"strings"
)
type WriteFunc func(p []byte) (n int, err error)
func (wf WriteFunc) Write(p []byte) (n int, err error) {
return wf(p)
}
func myWrite(p []byte) (n int, err error) {
fmt.Print("%v", p)
return len(p), nil
}
func main() {
io.Copy(WriteFunc(myWrite), strings.NewReader("Hello world"))
}
TA贡献1810条经验 获得超4个赞
修复MyWriterFunction/MyWriteFunction错字。例如,
package main
import (
"fmt"
"io"
"os"
)
type FWriter struct {
WriteF func(p []byte) (n int, err error)
}
func (self *FWriter) Write(p []byte) (n int, err error) {
return self.WriteF(p)
}
func MyWriteFunction(p []byte) (n int, err error) {
// this function implements the Writer interface but is not named "Write"
fmt.Print("%v", p)
return len(p), nil
}
func main() {
MyFWriter := new(FWriter)
MyFWriter.WriteF = MyWriteFunction
// I want to use MyWriteFunction with io.Copy
io.Copy(MyFWriter, os.Stdin)
}
- 2 回答
- 0 关注
- 286 浏览
添加回答
举报