golang 中比较怪的写法

    xiaoxiao2022-07-05  164

    1. 函数做类型回调

    在github.com/golang/crypto/ssh/client_auth.go看到如下:

    type passwordCallback func() (password string, err error) func (cb passwordCallback) auth(session []byte, user string, c packetConn, rand io.Reader) (authResult, []string, error) { //... pw, err := cb() //在此处回调了 //... }

    2.  接收者和形参可以互相转化

    在github.com/golang/crypto/ssh/session.go看到如下:

    func (s *Session) start() error { //... type F func(*Session) for _, setupFd := range []F{(*Session).stdin, (*Session).stdout, (*Session).stderr} { setupFd(s) } // ... return nil } func (s *Session) stdin() { }

    e.g 1:

    type Student struct { } func (*Student) Study() { } type stufunc func(*Student) func main(){ s := &Student{} //注意这个的写法 var m stufunc = (*Student).Study m(s) }

     

    最新回复(0)