
Go by Example
Go by Example is a hands-on introduction to Go using annotated example programs. Check out the first example or browse the full list below. Unless stated otherwise, examples here assume …
Hello World - Go by Example
Now that we can run and build basic Go programs, let’s learn more about the language. Next example: Values . by Mark McGranaghan and Eli Bendersky | source | license
Go by Example: Functions
Functions are central in Go. We’ll learn about functions with a few different examples. package main: import "fmt" Here’s a function that takes two ints and returns their sum as an int. func …
: Generics - Go by Example
As an example of a generic function, SlicesIndex takes a slice of any comparable type and an element of that type and returns the index of the first occurrence of v in s, or -1 if not present. …
Go by Example: Slices
Slices are an important data type in Go, giving a more powerful interface to sequences than arrays. package main: import ("fmt" "slices") func main {Unlike arrays, slices are typed only by …
Go by Example: If/Else
Branching with if and else in Go is straight-forward. package main: import "fmt" func main {Here’s a basic example. if 7 % 2 == 0 {fmt. Println ("7 is even")} else {fmt. Println ("7 is odd")} You can …
Go by Example: Recursion
Go supports recursive functions. Here’s a classic example. package main: import "fmt" This fact function calls itself until it reaches the base case of fact(0). func fact (n int) int {if n == 0 {return …
Reading Files - Go by Example
Reading and writing files are basic tasks needed for many Go programs. First we’ll look at some examples of reading files. package main: import ("bufio" "fmt" "io" "os") Reading files requires …
Goroutines - Go by Example
To invoke this function in a goroutine, use go f(s). This new goroutine will execute concurrently with the calling one. go f ("goroutine") You can also start a goroutine for an anonymous …
Go by Example: Values
Go has various value types including strings, integers, floats, booleans, etc. Here are a few basic examples. package main: import "fmt" func main {Strings, which can be added together with +. …