我有以下的代码:
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
}
MyFWriter := new(FWriter)
MyFWriter.WriteF = MyWriteFunction
// I want to use MyWriteFunction with io.Copy
io.Copy(MyFWriter,os.Stdin)
我想做的是创建一个Writer接口来包装MyWriteFunction,因为它没有命名为“Write”,所以我无法将其与需要“Writer”接口的任何内容一起使用。以下代码会报错:
method MyWriterFunction is not an expression, must be called
我在这里做错了什么?如何设置WriteF为MyWriteFunction?
注意:我尽可能地简化了这个问题,在实际情况中,我有一个结构体,其中有MyWriteFunction和一个普通的Write函数,所以它变得有点复杂...(如果有更好的解决方法,我会很乐意听到!)
谢谢!!
编辑:我注意到了我的拼写错误并进行了更正(MyWriterFunction --> MyWriteFunction)。
我认为我过于简化了问题,以至于误导了您对我的原始意图。根据匿名评论和peterSO的友好评论,我重新创建了错误,以更好地演示我的问题:
package main
import (
"fmt"
"io"
"strings"
)
type ProxyWrite interface {
Write(p []byte) (n int, err error)
SpecialWrite(p []byte) (n int, err error)
}
type Implementer struct {
counter int
}
func (self Implementer) Write(p []byte) (n int, err error) {
fmt.Print("Normal write: %v", p)
return len(p),nil
}
func (self Implementer) SpecialWrite(p []byte) (n int, err error) {
fmt.Print("Normal write: %v\n", p)
fmt.Println("And something else")
self.counter += 1
return len(p),nil
}
type WriteFunc func(p []byte) (n int, err error)
func (wf WriteFunc) Write(p []byte) (n int, err error) {
return wf(p)
}
func main() {
Proxies := make(map[int]ProxyWrite,2)
Proxies[1] = new(Implementer)
Proxies[2] = new(Implementer)
/* runs and uses the Write method normally */
io.Copy(Proxies[1], strings.NewReader("Hello world"))
/* gets ./main.go:45: method Proxies[1].SpecialWrite is not an expression, must be called */
io.Copy(WriteFunc(Proxies[1].SpecialWrite), strings.NewReader("Hello world"))
}
我希望这能澄清我在第一次尝试中想要呈现的内容。
有什么想法吗?