英文:
Using Go packages
问题
我不确定如何调用Go包。例如,如果我想创建随机数,我应该导入"math/rand"
,但它不是"math"
库的一部分吗?那么为什么这段代码不起作用:
package main
import(
"fmt"
"math"
)
func main(){
r := rand.New(rand.NewSource(99))
fmt.Println(r)
}
我的意思是,我不能通过直接导入一个超类(在这种情况下,只是"math"
包)来访问随机函数吗?
英文:
I am not sure how Go packages are invoked. For example if I want to create random numbers I should import "math/random"
, but isn't it simply a part of the "math"
library? So why doesn't this piece of code work:
package main
import(
"fmt"
"math"
)
func main(){
r := rand.New(rand.NewSource(99))
fmt.Println(r)
}
I mean, can't I just directly access the random functions by simply importing a superclass (in this case, simply the math "math"
package)?
答案1
得分: 6
这是因为rand
是一个独立的包,位于math
包的层次结构下的math/rand
包中,所以你需要单独导入它:
package main
import (
"fmt"
"math/rand"
)
func main() {
r := rand.New(rand.NewSource(99))
fmt.Println(r)
}
英文:
Thats because rand
is a separate package that is hierarchically under the math
package math/rand
, so you have to import it specifically:
package main
import(
"fmt"
"math/rand"
)
func main(){
r := rand.New(rand.NewSource(99))
fmt.Println(r)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论