Katie Raby

Go - Packages, Variables & Printing


tags: golearnbeginners

Now that you've installed Go (see previous in series), follow me on the journey to writing your first Go program.

Find some of the key pieces of information you need to get started, such as how a Go file is structured, how to declare variables, and how to print.

Packages 📦

A good place to start in any Go journey is looking at the anatomy of a Go file, and understanding how Go files structure themselves using things called packages. Every Go program is made up of packages, and the main ( 😉 ) and most important package, where programs start running is called package main.

Packages are declared at the top of the file, and then below that you have any imports, which can either be grouped or split out (example below showing a single import).

Package names provide context for their usage, and when referred to elsewhere and accessing contents of a package, the package name is the prefix. i.e. fmt.Println() to access the Println function inside the fmt package.

Within the main package, you need a main function, which is the entry point for execution. An example main.go file looks like:

    // your package declaration
    package main

    // your import statements
    import "fmt"

    // main function - the entry point of execution
    func main() {
        fmt.Println("Hello, World.")

Note: it is best practice to only have one main package and method within a directory - as there should be only one entry point to a program.

The great thing i've found about Go is that so many handy packages are included by default in Go's standard library, such as Math and Testing. Find the full list of Go's standard library packages here.

helpful tip When you are playing around with Go, creating the files from scratch each time (rather than letting the IDE fill this for you) will help you to get used to the structure of a Go file.

Variables 🐾

One of the first things you're probably wondering is how to declare a variable in Go.

The var statement declares either a single variable, or a list of variables, with the type at the end. If no type is provided, Go will infer the type of the initialised variable.

      // declaring variable catYears as an integer
      var catYears int

      // initialising variable myCat to a string - type inferred
      var myCat = "Hansel"

      // declares two variables, both of type boolean
      var isCat, isDog bool

Variables can be written at package or function level. Inside a function, you can use the shorthand := syntax to declare and initialise a variable:

    func main() {
    // variable catYears declared and initialised using shorthand
      catYears := 12

You can find all the different basic types in go here. More of these will be covered later in the series.

Printing / Formatting 🖨

To print or format in Go, you can use the "fmt" package (pronounced fumpt, used in the hello world example above).

Below are some of the most commonly used functions for printing and formatting.

Print - writes to standard output (stdout) can accept multiple arguments, spaces are added between arguments when neither are strings, returns number of bytes written and any error encountered (n int, e error).

  • fmt.Print(args…) (n int, e error)
  • fmt.Println(args…) (n int, e error) each print-out is on a new line

    fmt.Print(1, true, 2)
    // 1 true 2

    // Hello
    // World

Sprint - does the same as Print, but returns the resulting string instead of printing it to stdout. In terms of usage, you may be saving the formatted string to a variable for example.

  • fmt.Sprint(args…) string
  • fmt.Sprintln(args…) string

    func main() {
      // resulting string is returned and saved into variable
      result := fmt.Sprint("Hello, World.")

      // Hello, World.

Similarly to the above, there is also Fprint which prints the result to an external source, such as a file.

Formatting Strings

  • Printf(format string, args…) (n int, err error)
  • Sprintf(format string, args…) string

Both fmt.Printf and fmt.Sprintf can be used for string interpolation / formatting strings.

What is string interpolation? "Evaluating a string literal containing one or more placeholders, yielding a result in which the placeholders are replaced with their corresponding values." (Wiki)

In short, you want a string to be dynamic and have values that could change, so, you put placeholders instead of static values.

In Go, these placeholders are also known as verbs. Both fmt.Printf and fmt.Sprintf expect a format string as their first argument - the format of the final string, including its verb placeholders.

An example of this in its basic form might look like:

    var myName = "Katie"

    // formatted string with %s as a placeholder for a string
    fmt.Printf("My name is %s", myName)

Find more resources with examples and verbs for formatting below!

Running a Go program

A good place to wrap this intro up, is how you actually run your Go code.

    $ go run filename.go

Don't forget that you can always use the Go Playground whenever you want to quickly try out a piece of code, or play around with something new!

Missed anything you think would be helpful to new Gophers? Send me a message! 💬

Back to posts