douji6735 2018-05-06 00:18
浏览 77
已采纳

去包装不带大写字母导出功能

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.

  • 写回答

1条回答 默认 最新

  • duandang2123 2018-05-06 00:30
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!