Golang函数指针作为结构的一部分
发布时间:2020-12-16 19:29:21 所属栏目:大数据 来源:网络整理
导读:我有以下代码: 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
我有以下代码:
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和一个正常写入函数的结构,所以它有点复杂…(如果有一个更好的方法来解决我的这个问题那么我很高兴听到它!) 谢谢!! EDIT ::我注意到我的打字错误并修复它(MyWriterFunction – > MyWriteFunction) 我认为我过分简化了这个问题,误导了我原来的意图. 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",nil } func (self Implementer) SpecialWrite(p []byte) (n int,err error) { fmt.Print("Normal write: %vn",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")) } 我希望澄清我第一次尝试提出的意思. 有什么想法吗?
你的代码中有一个打字错误,但是将func包装到一个结构体中也是不必要的.相反,您可以定义一个包装函数的WriteFunc类型,您可以定义Write方法.这是一个完整的例子.
package main import ( "fmt" "io" "strings" ) type WriteFunc func(p []byte) (n int,err error) { return wf(p) } func myWrite(p []byte) (n int,err error) { fmt.Print("%v",nil } func main() { io.Copy(WriteFunc(myWrite),strings.NewReader("Hello world")) } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |