Golang-为什么我不能在GOPATH/src/project中导入本地软件包,而不能在主目录中导入本地软件包? [英] Golang - Why can't I import local package in GOPATH/src/project but can in home directory?

查看:249
本文介绍了Golang-为什么我不能在GOPATH/src/project中导入本地软件包,而不能在主目录中导入本地软件包?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个项目,其文件夹结构如下:

I have a project, its folder structure is like following:

    /project
        models/
            Product.go
        main.go

main.go的内容是:

The content of main.go is:

package main

import (
    "./models"
    "fmt"
    "github.com/gin-gonic/gin"
)

func main() {
    r := gin.Default()
    fmt.Println(models.Product{})
    r.GET("/", func(c *gin.Context) {
        c.String(200, "he")
    })

    r.Run(":3000")
}

Product.go的内容为:

The content of Product.go is:

package models

type Product struct {
    Name string
}

我从键入go env得到的是:

GOARCH="amd64"
GOBIN=""
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GOOS="darwin"
GOPATH="/Users/Mac/go"
GORACE=""
GOROOT="/usr/local/Cellar/go/1.5.3/libexec"
GOTOOLDIR="/usr/local/Cellar/go/1.5.3/libexec/pkg/tool/darwin_amd64"
GO15VENDOREXPERIMENT=""
CC="clang"
GOGCCFLAGS="-fPIC -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -    fmessage-length=0 -fno-common"
CXX="clang++"
CGO_ENABLED="1"

当项目目录的位置为$GOPATH/src/project时,如果运行go run main.go,我得到的是以下错误消息:./main.go:: can't find import: "github.com/gin-gonic/gin".

When the location of the project directory is $GOPATH/src/project, If I run go run main.go, what I get is this error message: ./main.go:: can't find import: "github.com/gin-gonic/gin".

但是当项目目录的位置为~/project时,go run main.go可以正常工作.

But when the location of project directory is ~/project, go run main.go can work as expected.

我使用go1.5.3.

I use go1.5.3.

任何人都可以帮助我.谢谢.

Can anyone help me. Thanks.

推荐答案

相对导入路径仅是为了方便起见,主要用于实验. go buildgo install不完全支持它们.如果您想让包与go工具一起使用,请不要使用相对导入.按照如何编写Go代码中所述构造代码.

Relative import paths are only allowed as a convenience, mostly for experimentation. They are not fully supported by go build and go install. If you want your package to work with the go tools, don't use relative imports. Structure your code as described in How to Write Go Code.

这篇关于Golang-为什么我不能在GOPATH/src/project中导入本地软件包,而不能在主目录中导入本地软件包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆