DEV Community

Arthur Christoph
Arthur Christoph

Posted on

Go Series: The Way to Go

In this series, I'll start exploring Go language that I found useful and interesting in developing programs using Go.

Let's start with a Hello World program.
Any go program requires a package declaration. The package named main is special as it indicates that it is executable.
The main program in go can be named anything and usually called main.go.

package main

import (
    "fmt"
)

func main() {
  fmt.Println("Hello, World!")
}

Enter fullscreen mode Exit fullscreen mode

Beyond a simple program, we would need to include more packages. In the simple example above, we imported fmt package that is included in Go's standard library

To organize our code better, we can define a package in the folder structure of our app.

The steps are:

  1. Add go.mod file - this will turn our root folder into the root of the module. A module in go represents a collection of packages
  2. Inside the go.mod, add the module name, this name will be used when we import our package: module myapp
  3. Create a new folder where the new package will be defined, any file defined in this folder needs to be in the same package, otherwise go will complain. Let's call this package greeting. Note that the package name can be different than the folder name. To emphasize this, the package folder name is g
  4. Create a file hello.go as the first file that contains code for our greeting package
  5. Define functions that will be used in the main package, function Hi and Say are defined here, note that uppercase make these functions publicly accessible which is what we want
  6. Go back to main.go, then import the package, to do this, we need to specify the complete path which is: module name followed by the path to the package, so in our example the package is myapp and the package folder name is g. The best practice is to name it exactly as the package name which is greeting, but I want to show that when you import , the path is not the package name but the folder name of the package
import (
    "fmt"
    "myapp/g"
)
Enter fullscreen mode Exit fullscreen mode

I can use the package method by specifying the package name first followed by the function to invoke, this shows why the best practice is to name the folder the same as the package name - we have no idea what package name is unless we open the file first

fmt.Println(greeting.Hi())
Enter fullscreen mode Exit fullscreen mode

However, we can actually define an alias like:

import (
    x "myapp/g"
)
Enter fullscreen mode Exit fullscreen mode

Then I can call it:

fmt.Println(x.Hi())
Enter fullscreen mode Exit fullscreen mode

But the best practice is to make the package name equal to the folder, the g folder should be called greeting folder instead

  1. Run the program by running: go run . or go run main.go

This concludes the getting started with go. We'll explore more in the next post of this series

Top comments (0)