go 中的pacage 名称 和import {}中的名称
参考: 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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
1 2 3 4 5 6 7 8 9 | package p_f1 import ( "fmt" ) func F1() { fmt.Println( "package demo f1 func call" ) } |
f2.go
1 2 3 4 5 6 7 8 9 | 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, 报错:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
2017-07-20 开源软件Review Board