Go rand.Intn(10)で同じ数字が帰って来る件

初心者用メモ

最近あまり忙しくないのでGO言語を勉強したいと思います。(いまさら)

早速公式チュートリアルで勉強

A Tour of Go

二章あたりに進めたら"math/rand"をインポートしてランダム整数を出力する練習があるのだが、
何回実行しても同じ数字が帰って来る

左に解説が入っている:
Note: The environment in which these programs are executed is deterministic, so each time you run the example program rand.Intn will return the same number. (To see a different number, seed the number generator; see rand.Seed. Time is constant in the playground, so you will need to use something else as the seed.)

なるほどseedを更新しなければ行けないと

package main

import (
	"fmt"
	"math/rand"
	"time"
)

func main(){
	rand.Seed(time.Now().UnixNano())
	fmt.Println("Hello World !!", rand.Intn(100))
}

解決。

ちなみにA Tour of Go のプレイグランドで同じことをやってもtime.Now()が同じ値を返して来るので同じ数字が出て来るとのこと