Let's start by understanding the hello.go example
package main
import (
"fmt"
"golang.org/x/example/stringutil"
)
func main() {
fmt.Println(stringutil.Reverse("!selpmaxe oG ,olleH"))
}
hello.go include three parts: packages
, import
and func main()
.
The first statement of every go source file must be a package declaration.
Package is a way for collecting related Go code together.
A packages can have many files inside of it. For example:
main.go
// main.go
package main
import (
"fmt"
)
func main() {
fmt.Println("Hello MAIN!")
}
help.go
// help.go
package main
import (
"fmt"
)
func help() {
fmt.Println("Help!")
}
There are two type of packages
Use package name main
to specify this package can be compiled and then executed. Inside the main package, it must has a func call 'main'
Other package name defines a package that cab be used as a dependency.
We will discuss how to use reuseable packages later.
Use to import code from other packages.
Although there are some standard librariessuch as math, fmt ,debug ... etc.
We still need to use import to link the library to our package.
you can find out more standard libraries on golang.org/pkg
Besides, you can import third party packages from internet as well.
for example import "golang.org/x/example/stringutil"
This required you to install the package via command go get <package>
before building your own package.
The entry of our execuable code. This function is required for main package.