当我运行以下代码时,它在行中给出错误未定义的数学
fmt.Println("The square root of 4 is",math.Sqrt(4))
Run Code Online (Sandbox Code Playgroud)
但是,当我仅运行一种方法(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))
}
Run Code Online (Sandbox Code Playgroud)
正如沃尔克在评论中所说,导入math/rand并不导入math。你必须import "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
Run Code Online (Sandbox Code Playgroud)