未定义获取错误:使用math/rand库时go lang中的math

未定义获取错误:使用math/rand库时go lang中的math,go,Go,当我运行下面的代码时,它在行中给出了错误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()

当我运行下面的代码时,它在行中给出了错误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))
    }

正如沃尔克在评论中所说,导入
math/rand
并不导入
math
。您必须明确地导入“数学”

围棋不是一种解释性语言。导入在编译时解析,而不是在运行时解析。调用这两个函数中的哪一个,或者即使不调用其中任何一个,都无关紧要。代码不会以任何方式编译:

$ 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

导入“math/rand”只导入“math/rand”,而不导入“math”。如果要导入包数学,必须执行导入“数学”。这将防止单独运行foo(),不是吗?他声称只有foo()可以运行——也许你的IDE(如果你使用的话)会在你进行更改时自动更正导入?@Volker这是一个答案;你应该把它作为答案贴出来。