Go package not exporting function with capital letter
The native library Go "image" package does not have any New method.
You would need to prefix your own image package with the name of your project/path within $GOPATH
in order to make Go chose your own package, and not the native one.
See "Package names"
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:
import (
"context" // package context
"fmt" // package fmt
"golang.org/x/time/rate" // package rate
"os/exec" // package exec
)
The OP adds:
image
is in thesrc
folder: I have a folder calledimage
.
See "Organizing Go code":
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 theirGOPATH
to use the package.
Don't do this.
leme
Updated on June 04, 2022Comments
-
leme almost 2 years
I am trying to import a package in Golang, however I am unable to refrence a function declared within the package.
The following code is for the package i'm trying to import.
//image.go pacakage image import "pixel" type Image struct { Matrix [][]pixel.Pixel } func New(width, height int) *Image{ //Code }
The following code is for the main file
//main.go pacakage main import ( "image" "fmt" ) func main(){ img := image.New(10,4) fmt.Println(img) }
When I run the main.go with go run main.go I get an error that says
undefined: image.New
I have ensured that my function is defined with an uppercase letter so i'm unsure why I'm able to call the New function. I am however able to declare a new image.Image variable.
Edit:
The problem was that I was developing outside the designated GOPATH/src. I was creating a file outside the GOPATH and resetting my GOPATH to my work file. This prevented me from properly importing and compiling my packages.
-
tkausl almost 6 yearsIn which folder is
image.go
? -
leme almost 6 yearsin the src folder I have a folder called image
-
-
leme almost 6 yearsWould the proper way to import packages be hosting a repository and importing from the repository? For example, creating a github repo for the project and calling the package from the github url
-
VonC almost 6 years@leme without hosting the repo, simply having a local folder structure different from just "
image
" (likeGOPATH/src/myproject/image
) would allow your code to referencemyproject.image.New()
. You don't have to create a remote repo for that.