参考: https://groups.google.com/forum/#!topic/golang-nuts/oawcWAhO4Ow
Hi,
Nan Xiao <xiaona…@gmail.com> writes:
> (1) GOPATH="/root/go";
> (2) There is a folder whose name is "wire" in /root/go/src;
> (3) There is a file(a.go) in wire folder:
> package shark
What you describe, is a package "shark", with the import path
"wire". So:
> (4) hello.go:
Try instead:
> package main
>
> import (
> "wire"
> )
>
> func main() {
> shark.Hello()
> }
And now you know, why there is the strong suggestion, to have the
package name and the last component of the import path the same. From
this package main, there is *no way* to deduce, that shark.Hello() is
from the package with import path "wire", except looking at the
sourcecode.
My suggestion is:
a) Name the folder /root/go/src/shark (import path "shark") and the package shark
b) Name the folder /root/go/src/wire (import path "wire") and the package wire
c) Name the folder /root/go/src/wire/shark (import path "wire/shark") and the package shark
So, you are confused by there being *three* concepts:
a) the import path
b) the location on disk
c) the package name
a and b are *strongly* related (location = $GOPATH/importpath). But c is
only related to a and b by convention.
Best,
Axel
-------------------------------------------------------------------------------------------------------------------------------------------
import 中指定的名称,其实是 “包” 所在的路径(磁盘路径), package 的名称不一定要和所在的目录名称一样。
main.go
package main
import "fmt"
import (
// "../demo/f1"
"./f1" //import这里的,其实是磁盘路径名。
)
func say() {
fmt.Println("say function call!")
}
func main() {
fmt.Println("hello, world")
say()
// fly()
p\_f1.F1() //这里的和文件里面的 package 定义的报名一致就可以了。不一定要和目录名f1 同名, 可以随便命名,如这里的p\_f1.
//但是同一个目录下,不用的文件中的 package 定义的包名 也只能有一个!!
// f1.F2()
}
f1.go
package p_f1
import (
"fmt"
)
func F1() {
fmt.Println("package demo f1 func call")
}
f2.go
package p_f1
import (
"fmt"
)
func F2() {
fmt.Println("package f1 f2 func call.")
}
go run mian.go
稍微改一下,如果把f2.go 的第一行 package p_f1 改为 f1 , 运行: go run main.go, 报错:
手机扫一扫
移动阅读更方便
你可能感兴趣的文章