go - 从 GO 中的其他文件导入函数和结构?
问题描述
我是 GO 新手,刚开始尝试构建一个网络服务器来学习一些基础知识。我的main.go
文件变得非常臃肿,所以我想将主文件之外的一些函数和结构移动到像structures.go
和utilities.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 帖子提到你需要能够从其他文件导入东西。
解决方案
你不必导入任何东西。
路线.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
. 注意为您的文件夹使用小写字母。
推荐阅读
- mysql - 什么可能导致单线程内的 JPA 实体状态差异?
- python - 在 TensorFlow 中,如何沿参差不齐的维度索引 RaggedTensor?
- python - Python - 如何从列表中获取所有名称组合:TypeError:'list' object is not callable
- python - Python列表定义-根据条件插入或不插入元素
- go - 无法解释为什么“55”转换为“7”
- r - 我可以更改 RStudio 保存片段的位置吗?
- python - numpy "对象没有属性 "打开""
- java - Elasticsearch 6.4:XContentBuilder 在传递给 request.mapping() 时无法关闭
- reactjs - React/Typescript Route 组件字段类型错误
- javascript - 0 高度导航栏仍然可见?