English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutorial Básico do Golang

Controles de Fluxo do Golang

Funções & Métodos do Golang

Estruturas do Golang

Fatias & Arrays do Golang

Strings (String) do Golang

Ponteiros do Golang

Interfaces do Golang

Concorrência do Golang

Exceções do Golang (Error)

Outros itens do Golang

Número Aleatório do Linguagem Go (rand)

Podemos usar o objeto rand para gerar números aleatórios. Devemos fornecer algumas sementes para o objeto rand para que os números gerados sejam diferentes. Se não fornecermos sementes, o compilador sempre produzirá o mesmo resultado.

gerar número aleatório

package main
import "fmt"
import (
	"math/rand
	//"time"
	"time"
)
func main() {
	fmt.Print(rand.Intn(100))  //gerará de 0 a100 entre números inteiros
	fmt.Println()
	fmt.Print(rand.Float64())	//gerará de 0 a1número aleatório entre
	fmt.Println()
	rand.Seed(time.Now().Unix())  //Número aleatório gerado pelo Seed
	myrand := random(1, 20)
	fmt.Println(myrand)
}
func random(min, max int) int {
	retorna rand.Intn(max - min) + min
}

Saída:

81
0.9405090880450124
17