Go: Packages, Variables & Printing
Tags: go, beginners, journey, learning
Published: 2021-02-19 16:42:17

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:

```go
// 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](https://golang.org/pkg/). 

Which packages are your favourite? Let me know in the comments below! ⬇️ 

__*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.

```go
// 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:
```go
func main() { 
// variable catYears declared and initialised using shorthand
   catYears := 12
...
```

You can find all the different [basic types in go here](https://golang.org/pkg/go/types/#BasicKind). 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

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

fmt.Println("Hello")
fmt.Println("World")
// 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`

```go
func main() {
  // resulting string is returned and saved into variable
  result := fmt.Sprint("Hello, World.")
  
  fmt.Print(result)
  // 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:
```go
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! 
- [Verbs for formatting](https://golang.org/pkg/fmt/#hdr-Printing)
- [Go By Example - String Formatting](https://gobyexample.com/string-formatting)

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

```bash
$ go run filename.go
```

Don't forget that you can always use the [Go Playground](https://play.golang.org/) 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? Comment below!_ 💬