Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

go

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

FolderA-
-------- FileA.go
---------FileB.go

In FileB.go, I define method Foo()

In FileA.go, I want to call Foo() which defined in FileB.go.

Do I need to import FileB in FileA.go like this?

import ("FileB")
like image 631
BufBills Avatar asked Dec 02 '16 22:12

BufBills


2 Answers

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/

like image 80
oharlem Avatar answered Nov 11 '22 20:11

oharlem


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.

like image 35
Kebeng Avatar answered Nov 11 '22 18:11

Kebeng