Code Splitting in Go

December 30, 2017    go golang best practices

In Go, all code revolves around the concept of packages. In this post, I’ll go through splitting code across the same package in Go. Essentially, if multiple files share the same package name, all exported functions share the same scope. This means we don’t need to use import to use any of these functions.

To demonstrate, create a file name hello.go -

package main

import "fmt"

func SayHello() {
    fmt.Println("Hello there!")
}

In the code above, we export a single function SayHello that prints out ‘Hello there!’ in the terminal. Line 1 is the important part. We are declaring this code as part of the main package. The function we exported is now scoped to the main package and we won’t have to use import to use this function.

Create the main file, name main.go -

package main

func main() {
    SayHello()
}

Run the code with go run *.go and you should ‘Hello there!’ printed out. And that’s it! You can find this example code on GitHub.



comments powered by Disqus