Golang function pointer as a part of a struct

前端 未结 2 993
夕颜
夕颜 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:31

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

提交回复
热议问题