Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go package not exporting function with capital letter

Tags:

import

package

go

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.

like image 261
leme Avatar asked Mar 03 '26 00:03

leme


1 Answers

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 the src folder: I have a folder called image.

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 their GOPATH to use the package.
Don't do this.

like image 120
VonC Avatar answered Mar 04 '26 15:03

VonC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!