Golang function pointer as a part of a struct

前端 未结 2 1028
夕颜
夕颜 2021-01-31 19:41

I have the following code:

type FWriter struct {
    WriteF func(p []byte) (n int,err error)
}

func (self *FWriter) Write(p []byte) (n int, err error) {
    ret         


        
2条回答
  •  暖寄归人
    2021-01-31 20:22

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

提交回复
热议问题