gpt4 book ai didi

go - 获取错误未定义 : math in go lang when using math/rand library

转载 作者:IT王子 更新时间:2023-10-29 01:40:50 25 4
gpt4 key购买 nike

当我运行下面的代码时,它在行中给出错误 undefined math

fmt.Println("The square root of 4 is",math.Sqrt(4))

然而,当我只运行一个方法(foo 或 boo)时,没有给出错误。

package main 

import ("fmt"
"math/rand")

func main() {
boo();
foo();

}

func boo() {
fmt.Println("A number from 1-100",rand.Intn(100))
}
func foo() {

fmt.Println("The square root of 4 is",math.Sqrt(4))
}

最佳答案

正如 Volker 在评论中所说,导入 math/rand 不会导入 math。您必须明确地导入“math”

Go 不是一种解释型语言。导入是在编译时解决的,而不是在运行时。您调用这两个函数中的哪一个都没有关系,即使您不调用其中任何一个也没有关系。代码不会以任何一种方式编译:

$ nl -ba main.go 
1 package main
2
3 import (
4 "fmt"
5 "math/rand"
6 )
7
8 func main() {
9 }
10
11 func boo() {
12 fmt.Println("A number from 1-100", rand.Intn(100))
13 }
14 func foo() {
15 fmt.Println("The square root of 4 is", math.Sqrt(4))
16 }
$ go build
# _/tmp/tmp.doCnt09SnR
./main.go:15:48: undefined: math

关于go - 获取错误未定义 : math in go lang when using math/rand library,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52094671/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com