我的站点

一个系统软件工程师的随手涂鸦

Category: Go语言实践技巧 (Page 1 of 2)

Go语言实践技巧(16)——打印结构体使用“%+v”

Go语言中打印结构体推荐使用“%+v”,而不是“%v”。看一下二者区别:

package main

import "fmt"

type info struct {
    name string
    id int
}

func main()  {
    v := info{"Nan", 33}
    fmt.Printf("%v\n", v)
    fmt.Printf("%+v\n", v)
}

运行结果如下:

{Nan 33}
{name:Nan id:33}

Go语言实践技巧(15)——禁止编译优化

如果要用gdbdelve等调试器调试Go程序,应该在编译时使用-gcflags "-N -l"禁止编译器优化,否则在调试代码时可能会观察到奇怪的现象。

参考资料:
Debugging Go Code with GDB
A question about using delve to print slice info.

 

Go语言实践技巧(14)——对channel进行操作时,如果对方永远没来,怎么办?

技巧出处:https://twitter.com/davecheney/status/631683117896495104

when sending or receiving on a channel, you must consider what happens if the other party never arrives.

 

Go语言实践技巧(13)——是否需要设置GOROOT和GOPATH?

技巧出处:https://twitter.com/davecheney/status/431581286918934528

Bf1I5MvCYAA3Ybb

Go语言实践技巧(12)——不要启动一个不知道何时会退出的goroutine

技巧出处:https://twitter.com/davecheney/status/714053897841577985

Never launch a goroutine without knowing how and when it will stop.

 

CemzcBBWwAEwfJe

Go语言实践技巧(11)——unbuffered channel

下列两种方式创建的都是unbuffered channel

ch = make(chan int)

ch = make(chan int, 0)

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

Page 1 of 2

Powered by WordPress & Theme by Anders Norén