I wonder if there is a way to use namespaces in the Go language in a similar way as Python does.
In Python if I have the following files containing functions:
/a.py
def foo():
/b.py
def bar():
I can access foo
and bar
in a third Python file as following:
import a
a1 = a.foo()
import b
b1 = b.bar()
I had some difficulties finding some documentation on namespaces with the Go language.
How are namespaces implemented in go? With package
and import
? Or is import
dedicated to external libraries?
I think I understood that for each package there should be a dedicated directory. I wonder if this is absolutely mandatory, because it can become impractical whenever a high granularity of modules is the best way to engineer a certain idea. In other words, I would like to avoid using one directory per package (for internal use).
Go's equivalent to Python modules are packages. Unlike Python modules that exist as a single file, a Go package is represented by a directory. While a simple package might only include a single source file in the directory, larger packages can be split over multiple files.
So to take your Python example, you could create a file $GOPATH/src/a/a.go
with the following contents:
package a
import "fmt"
func Foo() {
fmt.Println("a.Foo")
}
In your main program, you can call the function like so:
package main
import "a"
func main() {
a.Foo()
}
One thing to note is that only exported types and functions in a
will be available externally. That is, types and functions whose names begin with a capital letter (which is why I renamed foo
to Foo
).
If you don't want to set up a Go workspace, you can also use relative paths for your imports. For instance, if you change the import in the main program to import "./a"
, then the source code for the a
package can be located at a/a.go
relative to the main program.
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