为什么以下的 Golang 代码无法运行?

huangapple go评论75阅读模式
英文:

Why the following Golang code doesn't run?

问题

这段代码可以运行并生成一个从0到999的随机数:

package main

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

func main() {
	rand.Seed(time.Now().UnixNano())
	fmt.Println(rand.Intn(999))
}

但是下面的代码无法运行并报错:

代码:

package main

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

func main() {
	r := rand.Seed(time.Now().UnixNano())
	fmt.Println(r.Intn(999))
}

错误信息:

rand.Seed(time.Now().UnixNano()) 用作值

注意:我是新来的StackOverflow用户,如果问题不符合规则或标准,请原谅。

英文:

This code runs and gives a random number from 0 to 999:

package main

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

func main() {
	rand.Seed(time.Now().UnixNano())
	fmt.Println(rand.Intn(999))
}

But the following code refuses to run and gives an error

Code:

package main

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

func main() {
	r := rand.Seed(time.Now().UnixNano())
	fmt.Println(r.Intn(999))
}

Error message:
>rand.Seed(time.Now().UnixNano()) used as value

Note: I'm new to stackOverflow, so if the question isn't according to the rules or standards, please forgive me.

答案1

得分: 3

rand.Seed不返回任何值,它是一个无返回值的函数。

英文:

rand.Seed doesn't return any value, its a void function.

答案2

得分: 1

从godoc中:

Seed使用提供的种子值来初始化生成器为确定性状态。Seed不应与任何其他Rand方法并发调用。

这意味着它设置了一些种子来生成随机数,并且不返回任何值,但你尝试将其用作某个值。

英文:

From godoc

> Seed uses the provided seed value to initialize the generator to a
> deterministic state. Seed should not be called concurrently with any
> other Rand method.

That means, that it set some seed for generating random numbers and don't return anything, but you tried to use it as some value

答案3

得分: 0

rand.Seed是为rand.Intn函数做准备的。当你调用rand.Seed时,它会创建一个种子,稍后可以与rand.Intn一起使用。rand.Intn返回一个值,因此以下代码可以正常工作:

rand.Seed(time.Now().UnixNano())
fmt.Println(rand.Intn(999))

但是由于rand.Seed不返回任何值,对其调用rand.Intn会导致错误。

英文:

rand.Seed “sets up” rand.Intn, if you will. When you call rand.Seed, it creates a seed that can be used later with rand.Intn. rand.Intn returns a value, so

rand.Seed(time.Now().UnixNano())
fmt.Println(rand.Intn(999))

works. But since rand.Seed does not return a value, calling rand.Intn on it returns an error.

huangapple
  • 本文由 发表于 2017年1月13日 19:56:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/41634125.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定