Learn Go in Y Minutes: A Crash Course in Golang Programming
Learn Go in Y Minutes
Introduction
This is a crash course in the Go programming language. It covers the basics of syntax, data types, control flow, and concurrency.
Getting Started
Go is a statically typed, compiled language with a focus on simplicity and efficiency. It’s known for its built-in concurrency features and fast compilation times.
Package Declaration
Every Go source file starts with a package declaration. The main
package is special and declares an executable program.
package main
Import Declaration
Import declarations specify external packages used in the file.
import (
"fmt"
"io/ioutil"
m "math"
"net/http"
"os"
"strconv"
)
Functions
Functions are the building blocks of Go programs. The main
function is the entry point for executable programs.
The main
Function
func main() {
fmt.Println("Hello world!")
beyondHello()
}
Beyond Hello World
func beyondHello() {
var x int
x = 3
y := 4
sum, prod := learnMultiple(x, y)
fmt.Println("sum:", sum, "prod:", prod)
learnTypes()
}
Multiple Return Values
func learnMultiple(x, y int) (sum, prod int) {
return x + y, x * y
}
Data Types
Go has a variety of built-in data types, including integers, floats, strings, booleans, and more.
Basic Types
func learnTypes() {
str := "Learn Go!"
s2 := `A "raw" string literal
can include line breaks.`
g := 'Σ'
f := 3.14195
c := 3 + 4i
var u uint = 7
var pi float32 = 22. / 7
n := byte('\n')
}
Arrays and Slices
func learnTypes() {
var a4 [4]int
a3 := [...]int{3, 1, 5}
s3 := []int{4, 5, 9}
s4 := make([]int, 4)
var d2 [][]float64
bs := []byte("a slice")
}
Appending to Slices
func learnTypes() {
s := []int{1, 2, 3}
s = append(s, 4, 5, 6)
fmt.Println(s)
s = append(s, []int{7, 8, 9}...)
fmt.Println(s)
}
Pointers
func learnMemory() (p, q *int) {
p = new(int)
s := make([]int, 20)
s[3] = 7
r := -2
return &s[3], &r
}
Maps
func learnTypes() {
m := map[string]int{"three": 3, "four": 4}
m["one"] = 1
}
Control Flow
Go provides the standard control flow statements like if
, else
, for
, and switch
.
If Statements
func learnFlowControl() {
if true {
fmt.Println("told ya")
}
if false {
} else {
}
}
Switch Statements
func learnFlowControl() {
x := 42.0
switch x {
case 0:
case 1:
case 42:
case 43:
default:
}
}
For Loops
func learnFlowControl() {
for x := 0; x < 3; x++ {
fmt.Println("iteration", x)
}
for {
break
}
}
Range Loops
func learnFlowControl() {
for key, value := range map[string]int{"one": 1, "two": 2, "three": 3} {
fmt.Printf("key=%s, value=%d\n", key, value)
}
for _, name := range []string{"Bob", "Bill", "Joe"} {
fmt.Printf("Hello, %s\n", name)
}
}
Concurrency
Go’s built-in concurrency features make it easy to write programs that can take advantage of multi-core processors.
Goroutines
func inc(i int, c chan int) {
c <- i + 1
}
func learnConcurrency() {
c := make(chan int)
go inc(0, c)
go inc(10, c)
go inc(-805, c)
fmt.Println(<-c, <-c, <-c)
}
Channels
func learnConcurrency() {
cs := make(chan string)
ccs := make(chan chan string)
go func() { c <- 84 }()
go func() { cs <- "wordy" }()
select {
case i := <-c:
fmt.Printf("it's a %T", i)
case <-cs:
fmt.Println("it's a string")
case <-ccs:
fmt.Println("didn't happen.")
}
}
Error Handling
Go uses explicit error handling with the error
type.
The , ok
Idiom
func learnErrorHandling() {
m := map[int]string{3: "three", 4: "four"}
if x, ok := m[1]; !ok {
fmt.Println("no one there")
} else {
fmt.Print(x)
}
}
The error
Type
func learnErrorHandling() {
if _, err := strconv.Atoi("non-int"); err != nil {
fmt.Println(err)
}
}
Web Programming
Go’s net/http
package provides a simple and powerful way to build web servers and clients.
Starting a Web Server
func learnWebProgramming() {
go func() {
err := http.ListenAndServe(":8080", pair{})
fmt.Println(err)
}()
requestServer()
}
Handling Requests
func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("You learned Go in Y minutes!"))
}
Making Requests
func requestServer() {
resp, err := http.Get("http://localhost:8080")
fmt.Println(err)
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
fmt.Printf("\nWebserver said: `%s`", string(body))
}
Conclusion
This crash course provides a quick overview of the Go programming language. For a more in-depth understanding, refer to the official Go documentation and explore the vast resources available online.