英文:
How to import your own package?
问题
阅读了https://golang.org/doc/code.html,并查看了一些关于这个主题的StackOverflow问题后,我仍然无法构建一个包含多个文件的程序。
我的GOPATH是:C:/go_dev/
,我的目录结构如下:
go_dev/
src/
github.com/
aurelienCastel/
crashTest/
main.go
parser/
parser.go
main.go:
package main
import "github.com/aurelienCastel/crashTest/parser"
func main() {
info := parser.get_info_from("file.go")
// ...
}
parser/parser.go:
package parser
// ...
func get_info_from(file_name string) Info {
// ...
}
当我在crashTest
目录中运行go install
时,我得到以下错误:
> undefined: parser.get_info_from
我知道这是一个经常出现的问题,但有人能告诉我我做错了什么吗?
英文:
After reading https://golang.org/doc/code.html, and having a look at a few StackOverflow questions on the topic, I still can't build a program with several files in it.
My GOPATH is: C:/go_dev/
, and my directory structure is:
go_dev/
src/
github.com/
aurelienCastel/
crashTest/
main.go
parser/
parser.go
main.go:
package main
import "github.com/aurelienCastel/crashTest/parser"
func main() {
info := parser.get_info_from("file.go")
// ...
}
parser/parser.go:
package parser
// ...
func get_info_from(file_name string) Info {
// ...
}
When I run go install
in the crashTest
directory I get the following error:
> undefined: parser.get_info_from
I know this is a recurrent question, but could someone tell me what I am doing wrong?
答案1
得分: 4
为了使标识符能够从外部包中访问,其名称必须以大写字母开头。根据规范:
-
导出的标识符
标识符可以被导出以允许从另一个包中访问它。如果满足以下两个条件,则标识符被导出: -
标识符名称的第一个字符是一个 Unicode 大写字母(Unicode 类别 "Lu");
-
标识符在包块中声明,或者它是字段名或方法名。
所有其他标识符都不会被导出。
此外,按照 Go 的约定,标识符应使用混合大小写命名,而不是蛇形命名。
package parser
// ...
func GetInfoFrom(filename string) Info {
// ...
}
英文:
In order for an identifier to be accessible from an outside package, its name must begin with an uppercase letter. From the spec:
> ### Exported identifiers
An identifier may be exported to permit access to it from another package. An identifier is exported if both:
> - the first character of the identifier's name is a Unicode upper case letter (Unicode class "Lu"); and
- the identifier is declared in the package block or it is a field name or method name.
> All other identifiers are not exported.
Additionally, it is Go convention to name identifiers using mixed case, rather than snake case.
package parser
// ...
func GetInfoFrom(filename string) Info {
// ...
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论