Skip to content

Instantly share code, notes, and snippets.

@basti1302
Last active August 29, 2015 13:56
Show Gist options
  • Save basti1302/8997950 to your computer and use it in GitHub Desktop.
Save basti1302/8997950 to your computer and use it in GitHub Desktop.

Go Lab

Just some random things one could try to get acquainted with Go... only to be used if you lack the creativity to come up with your own ideas ;-)

Set up your environment

  1. Install Go
  2. Maybe configure your preferred text editor for Go

Hello World

Write a Hello World in Go :-)

Closures

Optional: Write a function that returns a new function. The latter is supposed to return the next Fibonacci number on each call. That is, fill out the missing parts here:

package main

import "fmt"

func fibonacci() func() int {
    // ???
    // Hint: Variables that are declared here are "attached" to the inner function instance and can be used to persist state across function calls.
    return func() int {
        // ???
    }
}

func main() {
    nextFibonacci := fibonacci()
    fmt.Println(nextFibonacci()) // 1
    fmt.Println(nextFibonacci()) // 1
    fmt.Println(nextFibonacci()) // 2
    fmt.Println(nextFibonacci()) // 3
    fmt.Println(nextFibonacci()) // 5
    fmt.Println(nextFibonacci()) // 8
}

Goroutines

Write a function that prints the elements of an array to stdout. Call this several times in parallel using goroutine. Here's a snippet for you to get you started.

package main

import (
    "fmt"
)

func print(arr []string) {
    for _, v := range arr {
        fmt.Println(v)
    }
}

func main() {
    // ???
}

Hint: Go does not wait for goroutines to finish before it terminates. If your program terminates prematurely, this SO answer might help.

Channels

Write two functions named send and receive, both taking a int channel (chan int) as their only argument. Make the send function write some integers to the channel. Make the receive function read from the channel and print the elements it reads to stdout. Call both in your main with the same channel object.

HTTP Server

  1. Write a simple http server that responds to every request with 200 OK and some text
  2. Write a simple http server that renders an html page (for example, by using package html/template)

Concurrent Processing

  1. Have that server read stuff from multiple files in parallel and report the content back (in the html output)
  2. Have the server call remote APIs (twitter, forecast.io, github, movie database, whatever you like) in parallel. Push the results of that into the html page.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment