A Note of Effective Go (Second Half)

Initialization

  • Constants
    用iota创建枚举常量
  • Variables
  • The init function

Methods

  • Pointers vs. Values
    The rule about pointers vs. values for receivers is that value methods can be invoked on pointers and values, but pointer methods can only be invoked on pointers. This is because pointer methods can modify the receiver; invoking them on a copy of the value would cause those modifications to be discarded.

Interfaces and other types

  • Interfaces
  • Conversions
    方便排序的能够做强制转换的sort.IntSlice()
  • Interface conversions and type assertions
    类型断言用来实现类似动态类型转换的功能
  • Generality
    返回接口而不是具体实现,可以清晰地表明行为比实现重要的设计理念。
  • Interfaces and methods

The blank identifier

  • The blank identifier in multiple assignment
  • Unused imports and variables
  • Import for side effect
    适用于只引用包,利用它的副作用而不使用其中名字的情况
  • Interface checks
var _ json.Marshaler = (*RawMessage)(nil) // Check if RawMessage implements json.Marshaler in compile time

Embedding

通过嵌入得到实现复用。

Concurrency

  • Share by communicating

Do not communicate by sharing memory; instead, share memory by communicating.

  • Goroutines
    相同地址空间,轻量级,在多个系统线程中复用。
  • Channels
  • Channels of channels
  • Parallelization
  • A leaky buffer

Errors

  • Panic
  • Recover

A call to recover stops the unwinding and returns the argument passed to panic. Because the only code that runs while unwinding is inside deferred functions, recover is only useful inside deferred functions.

recoverdeferred函数中与普通函数中的表现是不同的,在普通函数中总是返回nil,这就允许deferred函数可以正常调用其他库函数。

A web server

你可能感兴趣的:(A Note of Effective Go (Second Half))