首页 > 解决方案 > 从 GO 中的其他文件导入函数和结构?

问题描述

我是 GO 新手,刚开始尝试构建一个网络服务器来学习一些基础知识。我的main.go文件变得非常臃肿,所以我想将主文件之外的一些函数和结构移动到像structures.goutilities.go.

当我在 GoLand 中执行此操作时,它似乎会自动检测到它们并且我没有立即收到任何错误。但是,当我执行时,go run main.go我收到错误消息,说我的路由函数未定义。

这是我的目录的样子

-MyProject
--main.go
--routes.go
--structures.go
--go.mod

这是我go.mod文件中的内容

module <github_username>/<github_repo>

go 1.16

require github.com/gorilla/mux v1.8.0

main.go这是文件的当前开头

package main

import (
    "fmt"
    "github.com/gorilla/mux"
    "log"
    "net/http"
)

我也尝试将“路线”和“结构”添加到import块中,但出现错误Cannot resolve file <filename>

我不太清楚 Go 如何定位包,但也许这很重要,因为我的项目不位于~/User/<user>/go/src. 根据我在 Go 中引入模块模式的理解,你不必在那里有你的项目,但我可能完全错了。

任何建议将不胜感激!

编辑。

里面的所有函数routes.go都使用大写字母命名,因为我看到一个 SO 帖子提到你需要能够从其他文件导入东西。

标签: goweb

解决方案


你不必导入任何东西。

路线.go

package main

import "fmt"

func Routes() { // Capitalize function name to use it outside this file
  fmt.Println("Hello routes!")
}

main.go

package main

func main() {
  Routes() // Hello routes!
}

如果您在文件夹中有包 ie 文件,那么您可以使用该包名称调用该函数。示例:routes.Routes()。其中 routes 是一个包(文件夹)。在这种情况下,您必须导入import "<module that is defined in go.mod>/routes. 注意为您的文件夹使用小写字母。


推荐阅读