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

How to import a single go file in golang? Unable to import go file

正在尝试导入文件 go file 但无法导入。

我有一个主文件:

    main/
      main.go  
      go_single_file.go

package main

import (
"./go_single_file"
)

func main() {

}

go_single_file:

package go_single_file

func hello() bool{
return true
}

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

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

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

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

在 Golang 中,文件 organized 放入称为包的子目录中,以实现代码的可重用性。

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

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

.
├── main.go
├── go.mod
├── go_single_file
│   └── go_single_file.go

在您的 go_single_file.go 中,您没有将 exported names 用于函数 hello。所以你在 go_single_file/go_single_file.go 中的文件看起来像这样。

package go_single_file

func Hello() bool{
    return true
}

你的主文件是这样的

package main

import (
    "module_name/go_single_file"
)

func main() {
   _ = go_single_file.Hello()

}