使用Go包

huangapple go评论81阅读模式
英文:

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)

}

huangapple
  • 本文由 发表于 2014年12月25日 16:49:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/27645670.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定