在进行中,如果我们要使用该文件中定义的功能,是否不需要在同一目录中导入另一个文件?

Buf*_*lls 4 go

在进行中,如果我们要使用该文件中定义的功能,是否不需要在同一目录中导入另一个文件?例如。

FolderA-
-------- FileA.go
---------FileB.go
Run Code Online (Sandbox Code Playgroud)

在FileB.go中,我定义方法Foo()

在FileA.go中,我想调用FileB.go中定义的Foo()。

我需要像这样在FileA.go中导入FileB吗?

import ("FileB")
Run Code Online (Sandbox Code Playgroud)

Keb*_*eng 8

不,您不需要导入这些文件。将.go 一个目录下的所有文件视为一个包,将其下的目录视为另一个包。您可以从https://talks.golang.org/2014/organizeio.slide#1了解更多信息

因此,如果您想使用位于其他目录中的文件内部的另一个函数,则只需导入即可。

例如我们在一个fruit目录中有 2 个文件

苹果网

package fruit
import(fmt)

func ExportedMethod() {
    fmt.Print("apple")
}

func privateMethod() {}
Run Code Online (Sandbox Code Playgroud)

香蕉网

package fruit
import(fmt)

func banana() {
    fmt.Print("banana")
    ExportedMethod()
    pivateMethod()
}
Run Code Online (Sandbox Code Playgroud)

这两个文件在 Go 中被视为一个包,即使该方法未导出(第一个字符使用小写),您也可以从另一个文件调用方法,您可以在此处了解有关导出和未导出的更多信息https://www.goinggo.net/2014 /03/exportedunexported-identifiers-in-go.html

但即使认为已经导入了包,也banana.go需要导入包,因为包中的依赖项必须在使用它的每个文件上列出。fmtapple.gofmt


小智 6

不,只需调用一个函数。请注意:

  • 您不包含Go中的文件,而是包含包。
  • 这些文件应共享包。

检查以下内容:https : //blog.golang.org/organizing-go-code

谷歌也充满了很好的信息,例如。http://thenewstack.io/understanding-golang-packages/