当我运行以下代码时,它会在行中给出错误未定义的数学
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))
}
正如沃尔克在评论中所说,进口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