如何在golang中导入单个go文件?无法导入go文件

cod*_*x00 2 import go

尝试导入文件 go file 但无法执行此操作。

我有一个主要文件:

    main/
      main.go  
      go_single_file.go

Run Code Online (Sandbox Code Playgroud)
package main

import (
"./go_single_file"
)

func main() {

}

Run Code Online (Sandbox Code Playgroud)

go_single_file

package go_single_file

func hello() bool{
return true
}
Run Code Online (Sandbox Code Playgroud)

当我尝试导入go_single_file主文件时,出现某种导入错误。

我做错了什么但不确定是什么。

如果我制作一个单独的包并导入它,那么它可以工作,但如果它位于同一文件夹中则不行。

谁能告诉我如何从同一文件夹导入 go 文件。

Ham*_*nis 6

在 Golang 中,文件被组织到称为包的子目录中,从而实现代码的可重用性。

\n

Go 包的命名约定是使用我们放置 Go 源文件的目录的名称。在单个文件夹中,属于该目录的所有源文件的包名称都相同。

\n

我建议你使用 go 模块,你的文件夹结构应该是这样的。

\n
.\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 main.go\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 go.mod\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 go_single_file\n\xe2\x94\x82   \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 go_single_file.go\n
Run Code Online (Sandbox Code Playgroud)\n

在 go_single_file.go 中,您没有使用函数 hello 的导出名称。所以你里面的文件go_single_file/go_single_file.go看起来像这样。

\n
.\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 main.go\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 go.mod\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 go_single_file\n\xe2\x94\x82   \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 go_single_file.go\n
Run Code Online (Sandbox Code Playgroud)\n

你的主文件会像这样

\n
package go_single_file\n\nfunc Hello() bool{\n    return true\n}\n
Run Code Online (Sandbox Code Playgroud)\n