咖啡伴侣

呆在上海
posts - 163, comments - 156, trackbacks - 0, articles - 2

golang 之 接口

Posted on 2013-12-22 12:45 oathleo 阅读(4372) 评论(1)  编辑  收藏 所属分类: 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)是编译不过的

所以看到库里接口做参数类型定义的时候,可以简单认为,这个接口肯定是个对象指针(虽然也可以用对象,单估计没有哪个类库会用)

例如:
conn, err = ln.Accept()
go handleConnection(conn)

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

Feedback

# re: golang 之 接口  回复  更多评论   

2013-12-22 13:00 by 零柒锁业
期待更新啊

只有注册用户登录后才能发表评论。


网站导航: