【发布时间】:2014-01-10 19:28:49
【问题描述】:
我有以下代码:
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”接口的东西一起使用。
此代码无法正常工作,因为它抱怨:
方法 MyWriterFunction 不是表达式,必须调用
我在这里做错了什么?如何将WriteF 设置为MyWriteFunction?
注意:我尽可能地简化了这个问题,实际上我有一个结构体,它有 MyWriteFunction 和一个普通的 Write 函数,所以它有点复杂......(另外,如果有更好的方法解决我的这个问题,我会很高兴听到它!)
谢谢!!
编辑:我注意到我的错字并修正了它 (MyWriterFunction --> MyWriteFunction)。
我认为我过度简化了问题,误导了您的初衷。在匿名评论和 peterSO kind cmets 之后,我重新创建了错误以更好地展示我的问题:
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"))
}
我希望它澄清了我在第一次尝试时的意思。
有什么想法吗?
【问题讨论】:
-
你使用的是什么版本的 go?方法作为值直到 1.1 才出现。这段代码在操场上运行良好......play.golang.org/p/AmRi_fujPw
标签: function interface go writer