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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 标签(空格分隔): 编程 Go官方文档 Using the tour 1.1 Hello, 世界 Welcome...
    uangianlap阅读 5,441评论 0 5
  • 01.{ 换行: Opening Brace Can't Be Placed on a Separate Lin...
    码农不器阅读 7,009评论 0 14
  • 寻欢 “砰”的一声,身后的庙门紧紧的关上了。小和尚一行怔怔的站在寺庙门口的台阶上,沉甸甸的包袱挂在手上,像吊死鬼...
    牙床子阅读 3,532评论 7 5
  • 我永远相信物质生活只是改变了生活的状态,有多少人能因为富有或者成功就拥有全部的快乐?得到了多少荣耀必然付出过多少艰...
    雪落重阳阅读 4,101评论 21 11