英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论