关于导入:使用大写字母输出包不导出功能

Go package not exporting function with capital letter

我试图在golang中导入一个包,但是我无法引用包中声明的函数。

以下代码适用于我尝试导入的包。

1
2
3
4
5
6
7
8
9
10
11
//image.go
pacakage image
import"pixel"

type Image struct {
    Matrix [][]pixel.Pixel
}

func New(width, height int) *Image{
     //Code
}

以下代码用于主文件

1
2
3
4
5
6
7
8
9
10
11
//main.go
pacakage main
import (
   "image"
   "fmt"
)

func main(){
    img := image.New(10,4)
    fmt.Println(img)
}

当我运行main.go with go run main.go时,我得到一个错误,它说

1
undefined: image.New

我已经确保了我的函数是用大写字母定义的,所以我不确定为什么我能够调用这个新函数。但是,我可以声明一个新的image.image变量。

编辑:

问题是我在指定的gopath/src之外开发。我在gopath外创建了一个文件,并将gopath重置为我的工作文件。这使我无法正确导入和编译包。


本机库go"image"包没有任何新方法。

为了让Go选择自己的包,而不是本地包,您需要在自己的图像包前面加上$GOPATH中项目/路径的名称。

参见"包名称"

A Go package has both a name and a path.

The package name is specified in the package statement of its source files; client code uses it as the prefix for the package's exported names. Client code uses the package path when importing the package.
By convention, the last element of the package path is the package name:

1
2
3
4
5
6
import (
   "context"                // package context
   "fmt"                    // package fmt
   "golang.org/x/time/rate" // package rate
   "os/exec"                // package exec
)

OP增加:

image is in the src folder: I have a folder called image.

请参见"组织Go代码":

Sometimes people set GOPATH to the root of their source repository and put their packages in directories relative to the repository root, such as"src/my/package".

On one hand, this keeps the import paths short ("my/package" instead of"github.com/me/project/my/package"), but on the other it breaks go get and forces users to re-set their GOPATH to use the package.
Don't do this.