Golang function pointer as a part of a struct

耗尽温柔 提交于 2019-12-02 20:34:55

There's a typo in your code, but wrapping the func into a struct is unnecessary anyway. Instead, you can just define a WriteFunc type that wraps a function, and that you can define a Write method on. Here's a full example.

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"))
}

Fix MyWriterFunction/MyWriteFunction typo. For example,

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)
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!