假设我有一个包文件夹,如下所示:
hello
|---main.go
|---utilities.go
main.go
package main
utilities.go
package hello
我这样做是因为:
main.gohello
go list hello
无法加载包:包hello:在E:\ Workbench \ Go \ src \ hello中找到包main(main.go)和hello(utilities.go)
utilities.gogo list hellomain.go
你好
那么我必须将所有实用程序移动到另一个包文件夹吗?
main.go
ADD 1
ADD 2
import yyypackage xxx.a
因为我注意到了这些事实:
package xxxyyyimport yyyyyyxxx.Symbolyyy.Symbol
ADD 3
为了证实我在ADD 2中的猜测,我这样做了:
(以pkg1 \ file1.go)
package pkg2 // I deliberately use a different pkg name "pkg2" rather than the folder name "pkg1"
import "fmt"
func FA() {
fmt.Println("in the pkg2.FA")
}
(CMD1 \ main.go)
package main
import "pkg1"
func main() {
pkg2.FA() //here, the FA is referenced via "pkg2" rather than the "pkg1".
}
以上2个文件可以编译运行 .
但如果我改为:
(CMD1 \ main.go)
package main
import "pkg1"
func main() {
pkg1.FA() //here, the FA is referenced via "pkg1" as in the import statement. Should work, isn't it?
}
这将给出:
.... \ src \ cmd1 \ main.go:3:导入但未使用:“pkg1”为pkg2 .... \ src \ cmd1 \ main.go:6:undefined:pkg1 in pkg1.FA
go tool nm pkg1.apkg1.a.a
U
515 T %22%22.FA <========== this is my fuction FA
67b R %22%22.FA·f <========== this is my fuction FA
5eb T %22%22.init
67b B %22%22.initdone·
683 R %22%22.init·f
U fmt.Println
U fmt.init
673 R gclocals·33cdeccccebe80329f1fdbee7f5874cb
66b R gclocals·69c1753bd5f81501d95132d08af04464
65b R gclocals·e29b39dba2f7b47ee8f21f123fdd2633
64d R go.string."in the pkg2.FA"
63d R go.string.hdr."in the pkg2.FA"
7d2 R go.typelink.*[1]interface {}
796 R go.typelink.[1]interface {}
737 R go.typelink.[]interface {}
U runtime.algarray
U runtime.convT2E
6ec R runtime.gcbits.01
68b R runtime.gcbits.03
U runtime.morestack_noctxt
U runtime.throwinit
79a R type.*[1]interface {}
7d6 R type..importpath.fmt.
73b R type..namedata.*[1]interface {}.
6ed R type..namedata.*[]interface {}.
68c R type..namedata.*interface {}.
74e R type.[1]interface {}
6ff R type.[]interface {}
69c R type.interface {}
U type.string
所以到目前为止的结论是:
当声明的包名称是包文件夹名称中的 different 时,包声明将用作包的备用名称 .
相当于此,但隐含地:
import pkg2 "pkg1"
.a.go