Reputation: 63
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.
Upvotes: 3
Views: 31979
Reputation: 1324606
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.
Upvotes: 4