---
tags: Labs
---
# Lab 1: Introduction to Go
:::info
**Released:** Wednesday January 26, 2022.
**Due:** Sunday February 6, 2022 at 11:59PM ET.
:::
## Introduction
Welcome to CSCI 1951L! Throughout this course, you'll be using a programming language called Go to implement a blockchain. This lab is designed to help you set up your development environment and get you up to speed with the language you'll be using for the first three projects of the course: Chain, Coin, and Lightning!
A strong foundaion in Go is crucial to succeding in the course, so if you have any questions about this language, please ask the TA staff on EdStem or through the `#go-lab` Discord channel!
[TOC]
## Setup and Handin
### Setup
To get going with Go, first ensure that you have the Go programming language installed by running `go version` in the terminal. If you don't Go installed, follow the installation instructions [here](https://go.dev/doc/install). Please install Go 1.15 or above.
We ask that you use [GoLand](https://www.jetbrains.com/go/), a Go IDE with robust language support and debugging tools from JetBrains. If you've used IntelliJ or PyCharm before, it's the same IDE but for Go. There are instructions in HW0 on how to use your Brown email address to get a free license.
Once you have your development environment ready to go, **click [here](https://classroom.github.com/a/FKhjxr7W) to clone the stencil from Github Classroom.**
### Handin
- Make sure you submit the entire `lab1-go-<gitusername>` Go module (that is, the directory containing `go.mod`). Hand in your submission on Gradescope.
- Ensure you have written code for **Task 1** in `main.go`, **Task 2** in `lottery.go` and `lottery_test.go`, and **Task 3** in `linkedlist.go`.
- We highly recommend you use the Github submission method when submitting on Gradescope. You can also upload your submission as a zip file, but please ensure you are zipping the contents of the project directory instead of the folder itself:
![](https://i.imgur.com/hbGj8bv.png)
- You may submit as many times as you want before the deadline. Only your latest submission will be graded (though you will spend late days if the latest submission is after the due date.)
- **Do not modify function headers or parts of the stencil unless explicitly told to do so.** This ensures your submission works with the autograder.
- Questions or concerns? Ask on Discord.
## Part 1: Go Crash Course
In this section, we'll give a breif tour of the essential Go language features you'll need to know. Please use this section as a reference throughout the course, we think it will be very helpful!
### Hello World
Here is the classic "Hello, world!" program in Go:
```go=
package main
import "fmt"
func main() {
fmt.Println("Hello, world!")
}
```
Let's take a closer look at what we just wrote:
- The first line of every Go file must be the package it belongs in. In this case, **`main`**.
- Next are the packages that we import, identified by the **`import`** keyword.
:::success
**Task 1:** Type (not copy-paste) the above code in `main.go`, and run it by typing `go run main.go` in terminal. You should see "Hello, world!" print in the console.
:::
### Printing
The `fmt` package is the main package that provides functions for printing content out to the terminal.
`fmt.Println` prints a string out to the console:
```go=
fmt.Println("ur so good at go")
// ur so good at go
```
`fmt.Printf` prints a formatted string out to the console, similar to C's `printf`:
```go=
fmt.Printf("%d, %d, %d\n", 3, 2, 1)
// 3, 2, 1
```
Unlike C, Go provides a special format specifier `%v` that automatically prints a value using the default formatting. In the vast majority of cases, `%v` is the way to go.
```go=
fmt.Printf("%v, %v, %v\n", "big", 12.99, []int{12, 13, 14})
// big, 12.99, [12 13 14]
```
### Variables
Variables can be declared and initialized in one line using the `:=` operator:
```go=
z := 420 // Types are inferred.
a, b := 34, 35 // Can initialize multiple at a time!
```
You can also declare variables with/without initialization using the `var` keyword:
```go=
var x int
x = 10
var y = 11 // Types are inferred.
```
Constants are declared like variables, but with the `const` keyword. By convention, constants should be named using SCREAMING_SNAKE_CASE. They can be character, string, boolean, or numeric values. Constants cannot be declared using the `:=` syntax.
:::spoiler **See all of Go's basic types**
```go=
bool
string
int int8 int16 int32 int64
uint uint8 uint16 uint32 uint64 uintptr
byte // alias for uint8
rune // alias for int32, represents a Unicode code point
float32 float64
complex64 complex128
```
and their pointer variants, which are prefixed with a `*`. Each type has a zero value, which is `0` for numeric types, `false` for boolean types, and `""` for strings.
:::
### Functions
Functions are declared using the following syntax:
```go=
func sum(x int, y int) int {
return x + y
}
```
Use the `func` keyword, give the function a name, and type each of the parameters and outputs (notice that the type comes after the variable name).
When two or more consecutive named function parameters share a type, you can omit the type from all but the last:
```go=
func sum(x, y int) int {
return x + y
}
// noticed how we shortened x int, y int to x, y int
```
Functions can have multiple outputs and named return values:
```go=
func split(sum int) (x, y int) {
x = sum * 4 / 9
y = sum - x
return
}
```
:::info
Notice how we used `return` without arguments. A return statement without arguments returns the named return values. This is known as a "naked" return.
Naked return statements should be used only in short functions, as with the example shown above. They can harm readability in longer functions.
:::
Calling functions is rather straightforward as well:
```go=
fmt.Println(add(10, 11))
// 21
```
To have a function be invoked only when the calling function returns, use the `defer` keyword:
```go=
func doSomething() {
defer fmt.Println("world")
fmt.Println("Hello")
// Prints "Hello" then "world"
}
```
:::info
Deferred function calls are pushed onto a stack. When a function returns, its deferred calls are executed in last-in-first-out order.
To learn more about defer statements read this [blog post](https://go.dev/blog/defer-panic-and-recover).
:::
You can also define functions anonymously and inline:
```go=
isEven := func(x int) bool { return x % 2 == 0 }
```
### Control Flow
#### Loops
Go has only one looping construct, the `for` loop. There are two main ways to write a `for` loop, traditionally (like C) and using the range keyword:
```go=
for i := 0; i < 10; i++ {
fmt.Println(i)
}
primes := [6]int{2, 3, 5, 7, 11, 13}
for index, val := range primes {
fmt.Println(index, val)
}
```
:::warning
**Note:** Unlike other languages like C, Java, or JavaScript there are no parentheses surrounding the three components of the `for` statement and the braces `{ }` are always required.
:::
The init and post statements are optional.
```go=
func main() {
sum := 1
for ; sum < 1000; {
sum += sum
}
fmt.Println(sum)
}
```
Drop the semicolons and you have yourself Go's version of a `while` loop.
```go=
func main() {
sum := 1
for sum < 1000 {
sum += sum
}
fmt.Println(sum)
}
```
If you omit the loop condition it loops forever, so an infinite loop is compactly expressed as such:
```go=
for {
// do something forever...
}
```
#### If statements
The trusty `if` statement is written as follows:
```go=
x := 10
if x < 8 {
return 1
} else if x > 10 {
return 2
} else {
return 3
}
```
:::warning
**Note:** Similar to Go's for loops, the `if` statement expression need not be surrounded by parentheses ( ) but the braces { } are required.
:::
You can declare variables to be used in the `if` statement, but variables declared like this will be scoped to the `if` block, and be inaccessible outside of it:
```go=
if val := f(); val > 10 {
return true
}
fmt.Println(val) // will error
```
#### Switch statements
A `switch` statement is a more concise to write a sequence of `if - else` statements. It runs the first case whose value is equal to the condition expression.
Go's `switch` statement behaves similarly to the one in C, C++, Java, and JavaScript, except that Go only runs the selected case, not all of the cases that follow. In practice, this means the `break` statement needed at the end of each case in those languages is provided implicitly in Go. Another important difference is that Go's switch cases need not be constants, and the values involved need not be integers.
```go=
switch v {
case 10:
return false
case 12:
return true
default:
return false
}
```
### Pointers
Go has pointers. A pointer holds the memory address of a value. If you have never worked with pointers before, we recommend [reading up about C pointers](https://www.freecodecamp.org/news/pointers-in-c-are-not-as-difficult-as-you-think/) to get an idea of how they work (Go pointers are similar to C pointers, just without pointer arithmetic). The zero value of a pointer is `nil`. Define and dereference a pointer like so:
```go=
x := 10 // x holds 10
ptr := &x // ptr holds a reference to x
val := *ptr // val holds the value of x
```
You'll often see constructors that create pointers:
```go=
func NewKeyboard() *Keyboard {
return &Keyboard{switches: "Halo Clear", caps: "MATT3O MT3 SUSUWATARI"}
}
```
### Arrays, Slices, and Maps
#### Arrays
Arrays are fixed-size composite data types. The type `[n]T` is an array of `n` values of type `T`. Declare an array, filled with its zero value or initialized yourself, like so:
```go=
var names [2]string
primes := [6]int{2, 3, 5, 7, 11, 13}
```
:::info
Since the array's length is part of its type, they cannot be resized once declared.
:::
#### Slices
Slices are dynamically-sized views of an array; they are much more commonly used than arrays. The type `[]T` is a slice of values of type `T`. While there are many ways to define a slice, the most useful one uses the `make` function, while using the `append` function to add more elements to the slice:
```go=
names := make([]string, 0)
names = append(names, "sparky")
```
Use the `len` function to find the lengths of slices (and many other datatypes):
```go=
names := make([]string, 8)
length := len(names) // 8
```
#### Maps
Maps are key-value stores like Python dictionaries or Javascript objects. Declare and use a map like so:
```go=
m = make(map[string]int)
m["ten"] = 10
fmt.Println(m["ten"])
ten := m["ten"]
fmt.Println(ten)
delete(m, "ten")
fmt.Println(m["ten"]) // errors
ten_check, ok := m["ten"]
fmt.Println(ok) // false
fmt.Println(ten_check) // 0
```
:::spoiler **Checking if a value exists in a map**
An attempt to fetch a map value with a key that is not present in the map will return the zero value for the type of the entries in the map. For instance, if the map contains integers, looking up a non-existent key will return 0.
Sometimes you need to distinguish a missing entry from a zero value. You can do so with a form of multiple assignment.
```go=
if val, ok := dict["foo"]; ok {
//do something here
}
```
This is called the “comma ok” idiom. In this example, if `foo` is present, `val` will be set appropriately and `ok` will be true; if not, `val` will be set to zero and `ok` will be `false`.
To test for presence in the map without worrying about the actual value, you can use the blank identifier (`_`) in place of the usual variable for the value.
```go=
if _, ok := dict["foo"]; ok {
//do something here
}
```
:::
### Structs
A `struct` is a collection of fields:
```go=
type Coordinate struct {
x int
y int
z int
}
```
To initialize and print a `struct`, see the following example:
```go=
type Coordinate struct {
x int
y int
z int
}
func main() {
origin := Coordinate{x: 0, y: 0, z: 0}
fmt.Printf("%+v \n", origin)
}
// Prints {x:0 y:0 z:0}
```
Struct fields are accessed using a dot:
```go=
pos1 := Coordinate{x: 12, y: 24, z: 13}
fmt.Printf("%v \n", pos1.z) // prints 13
```
You can also create pointers to structs and access their fields in the exact same way (automatic dereferencing):
```go=
pos1 := &Coordinate{x: 12, y: 24, z: 13}
fmt.Printf("%v \n", pos1.y) // prints 24
```
You can define methods on structs (functions with a struct as a receiver) like so:
```go=
func (c Coordinate) printCurrentPosition() {
fmt.Printf("(%v, %v, %v)\n", c.x, c.y, c.z)
}
pos1 := Coordinate{x: 12, y: 24, z: 13}
pos1.printCurrentPosition() // prints "(12, 24, 13)"
```
Only methods that receive a pointer can mutate a struct:
```go=
// does nothing
func (c Coordinate) addX(d int) {
c.x += d
}
// yay!
func (c *Coordinate) addX(d int) {
c.x += d
}
```
### Interfaces
An interface is a set of method signatures. There is no `implements` keyword; the type system ensures that any struct that has a method for every method signature automatically implements the interface.
```go=
type Duck interface {
walk()
talk() string
}
```
The empty interface `interface{}` is implemented by every type, and is useful for when a type is unknown. We can cast from an `interface{}` type to another type (unsafely) using the `i.(type)` syntax:
```go=
anyMap := make(map[string]interface{}) // Can put anything in this map
anyMap["one"] = 1
anyMap["two"] = "two"
anyMap["three"] = Number{value: 3}
one := anyMap["one"].(int)
one := anyMap["one"].(string) // This will panic!
```
:::warning
One thing to note about interfaces is that an interface can be implemented by either a struct a pointer to that struct; as a result, you should almost never use a pointer to an interface in a function header, as it can cause some confusion:
```go=
func Wrong(i *SomeInterface) {} // This will not work as expected, even if your struct has pointer receiver methods
```
:::
### Errors
The error type is used to express errors. It is often returned by functions to signal whether or not the function ran as expected. The following is a very common pattern in Go:
```go=
func mightFail(input int) (int, error) {
if input == 0 {
return -1, errors.New("Can't use 0")
} else {
return 10 / input
}
}
func main() {
result, err := mightFail(0)
if err != nil {
return err
}
fmt.Println(result)
}
```
### Concurrency
Concurrency is a whole other topic that is beyond the scope of this lab. We are going to breifly go over the Go-specific constructs and features for writing concurrent programs, but if you're a bit confused with concurrency in general, please ask in Discord or EdStem!
#### Goroutines
A goroutine is a lightweight thread managed by the Go runtime. You can start a new goroutine using to `go` keyword as such:
```go=
go f(x, y, z)
```
This code starts a new goroutine running:
```go=
f(x, y, z)
```
The evaluation of `f`, `x`, `y`, and `z` happens in the current goroutine and the execution of `f` happens in the new goroutine.
Goroutines run in the same address space, so access to shared memory must be synchronized. The `sync` package provides useful primitives, although you won't need them much in Go since Go provides a useful primative: channels.
#### Channels
Channels are a typed conduit through which you can send and receive values between goroutines with the channel operator, `<-`.
```go=
ch <- v // Send v to channel ch.
v := <-ch // Receive from ch, and
// assign value to v.
```
(The data flows in the direction of the arrow.)
Like maps and slices, channels must be created before use:
```go=
ch := make(chan int)
```
By default, sends and receives block (that is, pauses the current thread of execution) until the other side is ready. This allows goroutines to synchronize without explicit locks or condition variables.
The example code sums the numbers in a slice, distributing the work between two goroutines. Once both goroutines have completed their computation, it calculates the final result.
```go=
package main
import "fmt"
func sum(s []int, c chan int) {
sum := 0
for _, v := range s {
sum += v
}
c <- sum // send sum to c
}
func main() {
s := []int{7, 2, 8, -9, 4, 0}
c := make(chan int)
go sum(s[:len(s)/2], c)
go sum(s[len(s)/2:], c)
x, y := <-c, <-c // receive from c
fmt.Println(x, y, x+y)
}
```
By default channels are *unbuffered*, meaning that they will only accept sends (`chan <-`) if there is a corresponding receive (`<- chan`) ready to receive the sent value. Buffered channels accept a limited number of values without a corresponding receiver for those values. Provide the buffer length as the second argument to `make` to initialize a buffered channel:
```go=
ch := make(chan int, 100)
```
Because this channel is buffered, we can send these values into the channel without a corresponding concurrent receive. Later we can receive these two values as usual.
A sender can close a channel to indicate that no more values will be sent. Receivers can test whether a channel has been closed by assigning a second parameter to the receive expression:
```go=
v, ok := <-ch
```
When `ok` is `false` if there are no more values to receive and the channel is closed.
:::warning
**Note:** Only the sender should close a channel, never the receiver. Sending on a closed channel will cause a panic.
**Anotha one:** Channels aren't like files; you don't usually need to close them. Closing is only necessary when the receiver must be told there are no more values coming, such as to terminate a range loop.
:::
#### Mutex
As mentioned earlier, the `sync` package provides a bunch of useful primatives.
If we don't need the communication channels provide, and instead we just want to make sure only one goroutine can access a variable at a time, we can use a mutex. The `sync` package provides `sync.mutex`, alongside the corresponding `Lock` and `Unlock` methods.
```go=
// Inc increments the counter for the given key.
func (c *SafeCounter) Inc(key string) {
c.mu.Lock()
// Lock so only one goroutine at a time can access the map c.v.
c.v[key]++
c.mu.Unlock()
}
```
We can also use the `defer` keyword we saw earlier to ensure the mutex will be unlocked:
```go=
// Inc increments the counter for the given key.
func (c *SafeCounter) Inc(key string) {
c.mu.Lock()
// Lock so only one goroutine at a time can access the map c.v.
defer c.mu.Unlock()
c.v[key]++
}
```
### Testing
Unit tests in Go are written in files that end in `_test.go`. Typically, unit tests for a given package live in the same folder as the package itself. Unit tests are simply functions that begin with `Test` and take one parameter of type `*testing.T`. You can run all of the tests for a given package using `go test [-v]`. The following is an example test:
```go=
func TestAdd(t *testing.T) {
a, b := 10, 11
if a + b != 21 {
t.Error("Addition is broken")
}
}
```
## Part 2: Now It's Your Turn!
Now let's see what you've learned! In this section, you will design a simple lottery system. Your system should be able to:
* Add players (by name) to the player pool.
* Each player can only be registered once, so return an error if the same user tries to register more than once.
* Remove players from the player pool.
* Return an error if the user being removed isn't registered in the player pool.
* Pick a winner at random.
* Remove the winner from the player pool.
* See the [`math/rand`](https://pkg.go.dev/math/rand) package.
* Return an error if there are no registered players to draw from.
:::success
**Task 2:** In `lottery.go`, implement the system described above using the provided structs, methods, and helpers. Make sure you write corresponding tests in `lottery_tests.go`. Make sure you handle errors appropriately in your tests.
**Feeling extra?** See if you can get all operations (that is, `AddPlayer`, `RemovePlayer`, and `PickWinner`) to be `O(1)`. This isn't required for credit, but give it a try 😉!
:::
## Part 3: Debugging
To learn more about the GoLand debugger, read this [useful article](https://blog.jetbrains.com/go/2019/02/06/debugging-with-goland-getting-started/).
:::success
**Task 3:** In `linkedlist.go`, you will find a basic implementation of a Linked List, alongside `Insert`, `Search`, `GetAt`, and `Print` functions. You can also find tests in `linkedlist_test.go`. Run the test suite (by typing `go test ./linkedlist` or clicking the play button in GoLand), and notice that the tests don't pass. Use the debugger to find the bug and fix it.
:::
## Helpful Things
### Style & Tips
- You might notice that Go doesn't require semicolons; it is considered poor style to include them unless when necessary.
- The `interface{}` type is the "Any" type in Go. All other types implement it. To cast an `interface{}` variable to another type, use the dot syntax. e.g. `x.(int)` casts `interface{}` variable `x` to an `int`.
- Typically, you want to access struct attributes using getters and setters; avoid accessing them directly with the dot operator.
- To return an error, use the errors package: `errors.New("this is an error")`. Our autograder does not care what error string you write, just that an error is thrown when expected.
- You can alternatively use `fmt.Errorf` as such: `fmt.Errorf("some error occured: %v\n", err)`
- To cast any value to a string, use `fmt.Sprintf("%v\n", x)`. This code returns a string version of `x`.
### Additional Resources
- [Go by Example](https://gobyexample.com/)
- [A Tour of Go](https://go.dev/tour)
- [Effective Go](https://go.dev/doc/effective_go)
- [CSCI 1380's Get Going With Go](http://cs.brown.edu/courses/csci1380/s21/content/docs/get-good-with-go.pdf)