go code snippet - ltoddy/blog GitHub Wiki

Golang

1. 使用枚举

type MobilePlatform string

const (
	IOS     = MobilePlatform("ios")
	Android = MobilePlatform("android")
)

在代码中尽可能的多使用枚举,来替换字面量代码。

由于Go语言目前并没有提供enum这样的关键字来定义枚举。 但又提供了type alias功能。所以,借助于type alias功能, 以及IDE自带的lint功能。即实现枚举的效果,也可以帮助lint做类型检查。

同时,使用type alias,对于结构体序列化无影响。

2.为数组添加方法。

目前来说,Go语言还没有孤儿原则,所以借助于type alias可以实现一些可读性更好 的代码设计。

// TODO:

3.使用语义化的类型

在平常工作中,最常见,从数据库中按条件查询出一个集合的数据,然后转成HashMap这样的数据结构。

比如,有一个User表, 表中有id,name,age等等这样的字段。

type User struct {
	Id   uint   `json:"id"`
	Name string `json:"name"`
	Age  int    `json:"age"`
}

想要转成一个HashMap,其key为user id,value为user,那么便可以:

type UserId = uint

var usersInfo map[UserId]User

这样写。

那么,当鼠标放到变量usersInfo上的时候,IDE会提示类型,那么一目了然就明白它的含义了。

4. channel的使用

func Producer() <-chan interface{} {
	results := make(chan interface{})

	go func() {
		defer close(results)
		//	do something
	}()

	return results
}

func Consumer(results <-chan interface{}) {
	for {
		select {
		case result := <-results:
			// do something with `result`
		}
	}
}
⚠️ **GitHub.com Fallback** ⚠️