Go语言实践技巧(10)——type literal

根据Go语言规范

A type determines the set of values and operations specific to values of that type. Types may be named or unnamed. Named types are specified by a (possibly qualified) type name; unnamed types are specified using a type literal, which composes a new type from existing types.

可以理解为,unnamed types就被称作type literal

 

Go语言实践技巧(9)——计算时间差

这个技巧来自:https://twitter.com/davecheney/status/718020797734866944。计算时间差的代码如下:

package main
import (
    "time"
    "fmt"
)

func main()  {
    t1 := time.Now()
    time.Sleep(5 * time.Second)
    fmt.Println(time.Since(t1))
} 

执行结果如下:

5.0005s

time.Since(t)time.Now().Sub(t)shorthand.

 

Go语言实践技巧(8)——channel类型

声明channel时,<-表明方向:

chan T          // 能收发`T`类型变量
chan<- float64  // 只能发送 float64 类型变量 (write-only)
<-chan int      // 只能接收 int 类型变量 (read-only)

<-同最左边的channel结合:

chan<- chan int    // 同 chan<- (chan int)
chan<- <-chan int  // 同 chan<- (<-chan int)
<-chan <-chan int  // 同 <-chan (<-chan int)

参考资料:
How to understand “<-chan” in declaration?

Go语言实践技巧(7)——value receiver和pointer receiver

Value receiver:

func (u user) fun1() {
    ....
}

Pointer receiver:

func (u *user) fun2() {
    ....
}

Value receiver操作的是值的拷贝,而pointer receiver操作的是实际的值。

pointer去调用value receiver的方法,实际的操作是:

(*p).fun1()

而用value去调用pointer receiver的方法,实际的操作是:

(&v).fun2()

参考资料:
Go in Action