golang 接口 参数

conn, err = ln.Accept()
go handleConnection(conn)

看到这里我曾经有个疑问,为何不是  handleConnection(&conn) ?函数

package main

import (
    "fmt"
)

type Interface interface {
    say() string
}

type Object struct {
}

func (this *Object) say() string {
    return "hello"
}

func do(i Interface) string {
    return i.say()
}

func main() {
    o := Object{}
    fmt.Println(do(&o))
    fmt.Printf("CCCCCCCCCCC:%T", o)
}

函数的参数以接口定义,编译器会本身判断参数是对象仍是对象的指针
好比,say是指针上的方法,因此do只接受Object的指针作参数,do(o)是编译不过的

因此看到库里接口作参数类型定义的时候,能够简单认为,这个接口确定是个对象指针(虽然也能够用对象,单估计没有哪一个类库会用)this

例如:
指针

conn, err = ln.Accept()
go handleConnection(conn)

这里conn是个接口,不须要 go handleConnection(&conn)
code

相关文章
相关标签/搜索