in go, don't we need to import another file in same directory if we want to use function defined in that file?

No. Just call a function. Please note:

  • You are not including files in Go, you include packages.
  • These files should share the package.

Check this: https://blog.golang.org/organizing-go-code

And google is full of good info as well, ex. http://thenewstack.io/understanding-golang-packages/


No you don't need to import those files. Go treat all .go file in one directory as one package and directory under it as another package. you can learn more from https://talks.golang.org/2014/organizeio.slide#1

So you only need to import if you want to use another function that locate inside files in other directory.

for example we have 2 files inside one fruit directory

apple.go

package fruit
import(fmt)

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

func privateMethod() {}

banana.go

package fruit
import(fmt)

func banana() {
    fmt.Print("banana")
    ExportedMethod()
    pivateMethod()
}

those two files is treated as one package in Go and you can call method from another file even the method is unexported (using lowercase at first character) you can learn more about exported and unexported here https://www.goinggo.net/2014/03/exportedunexported-identifiers-in-go.html

but banana.go need to import fmt package even thought apple.go is already import the fmt package because dependencies in package must be listed specific on each file that uses it.

Tags:

Go