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

huangapple go评论78阅读模式
英文:

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

问题

尝试导入一个Go文件,但无法成功。

我有一个主文件:

    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文件吗?

英文:

Trying to import a file go file but unable to do so.

I have one main file:

    main/
      main.go  
      go_single_file.go

package main

import (
"./go_single_file"
)

func main() {

}

and go_single_file:

package go_single_file

func hello() bool{
return true
}

when i try to import go_single_file in my main file i get some sort of import error.

I am doing something wrong but not sure what.

If i make a separate package and import it then it works but not if it's in same folder.

Can anyone tell how can i import a go file from same folder.

答案1

得分: 6

在Golang中,文件被组织成称为包的子目录,这样可以实现代码的可重用性。

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

我建议您使用Go模块,并且您的文件夹结构应该像这样。

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

在您的go_single_file.go文件中,您没有为函数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()

}
英文:

In Golang files are organized into subdirectories called packages which enables code reusability.

The naming convention for Go package is to use the name of the directory where we are putting our Go source files. Within a single folder, the package name will be same for the all source files which belong to that directory.

I would recommend you to use go modules and your folders structure should be like this.

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

In your go_single_file.go you are not using exported names for the function hello. So your file inside the go_single_file/go_single_file.go would look like this.

package go_single_file

func Hello() bool{
    return true
}

Your main file would like this

package main

import (
    "module_name/go_single_file"
)

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

}

huangapple
  • 本文由 发表于 2022年3月3日 04:20:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/71328677.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定