西维蜀黍

【Golang】使用 - 生成随机数

GoLang 中的伪随机数

GoLang 中,我们可以通过 math/rand 包里的方法来生成一个伪随机数:

package main

import (
  "fmt"
  "math/rand"
)

func main() {
  fmt.Println(rand.Int())   // => 5577006791947779410
}

上面的代码中,我们通过 rand.Int() 方法来生成一个伪随机数。看起来好像没什么问题嘛,人家也很 OK 啦。

但是细心的你会发现。无论你运行多少次,它都会生成一样的结果。

我们知道 JavaScript 中的 Math.random() 每次都会返回一个不一样的数字,但是 GoLang 中的伪随机数生成器默认情况下竟然会返回相同的数值,这还不反了天了?

都是伪随机数生成器,为什么差别就这么大呢?这里我们就要了解一下“随机种子”的概念啦。

  ...


【Git】忽略已经提交的文件

Situaion

在初始化git仓库的时候,没有创建.gitignore文件来过滤不必要提交的文件,后来却发现某些文件不需要提交,但是这些文件已经被提交了。

这时候创建.gitignore文件并添加对应规则以忽略这些文件,就会发现,对这些文件的修改仍然会被 track到,即忽略ignore的规则对那些已经被track的文件无效。

其实.gitignore文件只会忽略那些没有被跟踪的文件,也就是说ignore规则只对那些在规则建立之后被新创建的新文件生效。

因此推荐: 初始化git项目时就创建.gitignore文件

  ...


【Golang】Golang 版本管理

Installing multiple Go versions

You can install multiple Go versions on the same machine. For example, you might want to test your code on multiple Go versions. For a list of versions you can install this way, see the download page.

Note: To install using the method described here, you’ll need to have git installed.

To install additional Go versions, run the go install command, specifying the download location of the version you want to install. The following example illustrates with version 1.10.7:

$ go install golang.org/dl/go1.10.7@latest
$ go1.10.7 download

To run go commands with the newly-downloaded version, append the version number to the go command, as follows:

$ go1.10.7 version
go version go1.10.7 linux/amd64

When you have multiple versions installed, you can discover where each is installed, look at the version’s GOROOT value. For example, run a command such as the following:

$ go1.10.7 env GOROOT
  ...


【Golang】代码检查

易犯错误

幽灵变量(shadowed variables)

如果你在新的代码块中像下边这样误用了 :=,编译不会报错,但是变量不会按你的预期工作:

func main() {
	x := 1
	println(x)		// 1
	{
		println(x)	// 1
		x := 2
		println(x)	// 2	// 新的 x 变量的作用域只在代码块内部
	}
	println(x)		// 1
}

Solution: go-nyet

  ...


【Golang】幽灵变量(Shadowed Variables)

幽灵变量(Shadowed Variables)

Example 1

如果你在新的代码块中像下边这样误用了 :=,编译不会报错,但是变量不会按你的预期工作:

func main() {
	x := 1
	println(x)		// 1
	{
		println(x)	// 1
		x := 2
		println(x)	// 2	// 新的 x 变量的作用域只在代码块内部
	}
	println(x)		// 1
}

这是 Go 开发者常犯的错,而且不易被发现。

  ...