When I run the following code it gives the error undefined math in the line
fmt.Println("The square root of 4 is",math.Sqrt(4))
However when i run only one method (foo or boo) no error is given.
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))
}
As Volker said in the comments, importing math/rand
does not import math
. You have to import "math"
explicitely.
Go is not an interpreted language. Imports are resolved at compile time, not at runtime. It doesn't matter which of the two functions you call, or even if you don't call any of them. The code doesn't compile either way:
$ 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