如何导入自己的包?

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

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 installin the crashTestdirectory 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 {
    // ...
}

huangapple
  • 本文由 发表于 2016年12月12日 01:31:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/41088984.html
匿名

发表评论

匿名网友

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

确定