go - 如何导入我自己在 Go 的主包中定义的函数?

标签 go import

我是 Go 的新手,但我来自 C++ 学校。我只是想做一个项目,把逻辑拆分成多个文件。

在 C++ 中,我只需要将我的 main_file.cpp 放在一个

#include "my_own_lib.hpp" 

(类似于 Node.js 中的 module.exportsrequire('relative/path/to/my-own-lib'))

就是这样。在 Go 中,我遵循相同的逻辑,但我的结果是:

$ go run main.go
main.go:4:8: open /Users/mt/Documents/Codes/go/src/github.com/mt/Apollo/tst: no such file or directory

我的文件:

ma​​in.go

package main

import "fmt"
import "./tst"

func main() {
    fmt.Println("just testing")
    tst.p()
}

tst.go

package tst

import "fmt"

func p() {
    fmt.Println("ola")
}

当然我的文件结构是:

myFolder/
   |- main.go
   |_ tst.go

谁能告诉我这样做的正确方法是什么?

最佳答案

如果您也将 tst.go 的包设置为“package main”,您将能够在没有任何导入语句的情况下访问 p()。

$ cat main.go 
package main

func main() {
    p()
}
$ cat tst.go 
package main

import "fmt"

func p() {
    fmt.Println("ola")
}
$ go build ./ && ./test 
ola

我相信这会满足您的要求:

I just want to make a project and split the logic into many different files.

如果你正在构建一个程序而不是一个库,公认的 Go 约定是将你的所有文件作为“package main”:

The package “main” tells the Go compiler that the package should compile as an executable program instead of a shared library. http://thenewstack.io/understanding-golang-packages/

请解释您的反对意见

这里有一些著名的 Go 项目的例子,它们完全按照我说的做:

这些是代码拆分在多个 Go 文件中的可执行文件,所有这些文件都属于“package main”。

看到OP有点不清楚,你可以选择解释为他要创建一个外部包,tst。但他说得很清楚:

I just want to make a project and split the logic into many different files.

他说很多文件 - 不是很多外部包。他还说:

of course my file structure is:

myFolder/
   |- main.go
   |_ tst.go

我的建议是在这种情况下做事的正确方法:

executable/
   |- main.go (package main)
   |- a.go (package main)
   |- b.go (package main)

将应用程序拆分为 main、a 和 b。

关于go - 如何导入我自己在 Go 的主包中定义的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34967358/

相关文章:

python - 包含所有列名的 CSV 到 Python 字典?

java - 使用 Morphia 在 MongoDB 中批量更新插入。可能吗?

javascript - 发送带有 JQuery 脚本的 html 电子邮件

function - Golang MVC结构

mysql - 使用 std 为多对多关系建模结构

go - 在 golang 中使用发送网格?

struct - 如何创建不同类型的结构体数组的数组?

swift - Xcode忽略导入

Java错误包不存在

go - 声明一个类型,其中该类型是一个返回 struct{} 的函数