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

相關文章
相關標籤/搜索