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")
No. Just call a function. Please note:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With