gpt4 book ai didi

go - Go 中的相对导入

转载 作者:IT老高 更新时间:2023-10-28 13:04:02 27 4
gpt4 key购买 nike

我有一个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 workspaceor in a remote repository (explained below).

The packages from the standard library are given short import pathssuch as "fmt" and "net/http". For your own packages, you must choose abase path that is unlikely to collide with future additions to thestandard 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. Forinstance, if you have a GitHub account at github.com/user, that shouldbe your base path.

Note that you don't need to publish your code to a remote repositorybefore you can build it. It's just a good habit to organize your codeas if you will publish it someday. In practice you can choose anyarbitrary path name, as long as it is unique to the standard libraryand 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com