go - Go 中的相对导入

标签 go

我有一个go项目,目录结构如下

utils(pkg)
   | auth.go (has a function names test1)
controllers(pkg)
   | login.go (has a function names test2)

我正在尝试从 login.go 访问函数 test1。这是我所做的

import "../utils"

func test2(c *gin.Context) bool{
      utils.test1()
}

但我总是得到 Unresolved reference test1。我是新来的。谁能帮助我为什么会收到此错误?

最佳答案

Go 中没有相对导入。
考虑到 GOPATH,你应该使用绝对路径:

GOPATH 环境变量指定工作区的位置。它可能是您在开发 Go 代码时需要设置的唯一环境变量。首先,创建一个工作区目录并相应地设置 GOPATH。见:https://golang.org/doc/code.html#GOPATH

Import paths

An import path is a string that uniquely identifies a package. A package's import path corresponds to its location inside a workspace or in a remote repository (explained below).

The packages from the standard library are given short import paths such as "fmt" and "net/http". For your own packages, you must choose a base path that is unlikely to collide with future additions to the standard library or other external libraries.

If you keep your code in a source repository somewhere, then you should use the root of that source repository as your base path. For instance, if you have a GitHub account at github.com/user, that should be your base path.

Note that you don't need to publish your code to a remote repository before you can build it. It's just a good habit to organize your code as if you will publish it someday. In practice you can choose any arbitrary path name, as long as it is unique to the standard library and greater Go ecosystem.

示例:

本示例假设您已在操作系统环境中设置 GOPATH=/goworkdir

文件:goworkdir/src/project1/utils/auth.go

package utils

func Test1() string {
    return "Test1"
}

文件:goworkdir/src/project1/controllers/login.go

package controllers

import "project1/utils"

func Test2() string {
    return utils.Test1()
}

文件:goworkdir/src/project1/main.go

package main

import (
    "fmt"
    "project1/controllers"
)

func main() {
    fmt.Println(controllers.Test2())
}

现在如果你 go run main.go 你应该会看到输出:

Test1

关于go - Go 中的相对导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38517593/

相关文章:

go - 如何应用 kubernetes 工作负载

json - Martini 中的 JSON 编码错误

go - 在 Golang 中从 AWS S3 读取文件

string - 问:go-jira: slice 未在模板中 slice 字符串

go - 带有字符串名称的包选择器

go - 如何从 Golang 中的嵌套结构中获取值

go - K8S 通过 go API 读取 config map

go - 未定义的全局变量

在 Jenkins CI 中随机失败

go - 如何在 Ubuntu 中启动 Go 程序作为守护进程?