咖啡伴侣

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

2013年12月22日

package main

import (
    "fmt"
    "time"
)

var ch chan int = make(chan int, 1)

func main() {
    go aaa()

    select {
    case <-ch: //拿到锁
        fmt.Println("call")
    case <-time.After(5 * time.Second): //超时5s
        fmt.Println("5 sec call")
    }
}

func aaa() {
    time.Sleep(time.Second * 3)
    ch <- 1
}

posted @ 2013-12-24 13:03 oathleo 阅读(7260) | 评论 (0)编辑 收藏

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)

posted @ 2013-12-22 12:45 oathleo 阅读(4372) | 评论 (1)编辑 收藏