Who are the audience?
You have been programming for years and have heard some different types of languages.
You know what a static-typed language looks like and know Python.
Now, you want to pick up quickly and have a basic understanding of Go.
There is an official tutorial, but you still think it’s too long.
You’re at the right place.
Let’s start with a bird view of Go:
👉 Go is enhanced C with Python-flavour syntax
I know, I know, it’s definitely not an accurate summary of Go, C, and Python. It should give you a sense of what Go feels like.
The “enhanced C” parts tell you that Go is a static type language with pointers (oh no!).
The “Python-flavour” syntax tells you that Go is trying to make its syntax simple and elegant, just like Python.
Now, let's dive in!
How to use this article
Where to run Go code?
I highly recommend running on The Go Playground. Unlike Python you can create an arbitrary file and then Python
xxx.py
, it takes some extra work to run even “Hello World” with Go.
Life is short, use an online environment.
Code says more
I’ll use English only for elaborating. Reading through the code blocks should be a faster way to understand Go.
The code blocks are ready to run in The Go Playground.
Variables
Since Go is statically typed, a variable needs to be declared with type first and then to be used.
Luckily, you can combine a declaration with a assignment, and then skip the type part!
Code lives here: https://go.dev/play/p/RjO6MRPZ2T5
package main
import "fmt"
func main() {
/////////////////////////////////////////////////////////////////
var a int // declare that a is a int type variable
var b, c, d int // declare that b, c, d are int type variables
a = 1
b, c, d = 2, 3, 4
// Use `:=` operator to create a new variable concisely
e := 5 // e has type int
/////////////////////////////////////////////////////////////////
fmt.Println(a, b, c, d, e)
}
Python list
→ Go slice
Python’s list
is very handy! The similar thing in Go is slice
.
Code lives here: https://go.dev/play/p/3xNa_6STDOW
package main
import "fmt"
func main() {
/////////////////////////////////////////////////////////////////
var a []int // decalre a slice of int
// Using a composite literal to create a slice value
a = []int{1, 2, 3} // a is [1,2,3]
// Using make to create a slice value
a = make([]int, 3) // a is [0,0,0]
// Use `:=` operator
b := []int{4, 5, 6} // b is [4,5,6]
/////////////////////////////////////////////////////////////////
fmt.Println(a, b)
}
Go claims itself as a battery-included language. But a Python developer would laugh at it.
You’ll say why from the following examples of operations on slice
.
Code lives here: https://go.dev/play/p/9kWunOetFcC
package main
import (
"fmt"
"sort"
)
func main() {
/////////////////////////////////////////////////////////////////
a := []int{1, 2, 3}
// access an element
fmt.Println(a[0])
// slicing
b := a[1:3]
// appending
a = append(a, 4)
// inserting 0 between 2 and 3. Ew
a = append(a[:2], append([]int{0}, a[2:]...)...)
// removing 0 whose index is 2. Eww
a = append(a[:2], a[3:]...)
// popping the last one
c := a[len(a)-1]
a = a[:len(a)-1]
// sorting
sort.Ints(a)
// length
n := len(a)
/////////////////////////////////////////////////////////////////
fmt.Println(a, b, c, n)
}
Wait, I heard there is array
in Go?
You’re right. array
in Go is like array
in C. It has a fixed length. You can’t append an element to it. You can’t pop an element from it.
Actually, array
is more like the implementation of slice
, and slice
is the high-level interface of array
.
Python dict
→ Go map
Pretty much the same.
Code lives here: https://go.dev/play/p/wFrfHzkjyuZ
package main
import "fmt"
func main() {
/////////////////////////////////////////////////////////////////
a := map[int]string{}
a[1] = "1"
a[2] = "2"
// remove (1, "a") key-value pair
delete(a, 1)
// get the value of key 2, and check if the key is existing
v, exist := a[2] // v is "2" and exist is true
// or simply get the value if you're confident there is a key 2
v = a[2]
v, exist = a[3] // v is "" and exist is false
// v = a[3] will throw an error
/////////////////////////////////////////////////////////////////
fmt.Println(v == "", exist)
}
Python set
→ Go map
Sadly, there is not a similar thing in Go. You need to implement it by yourself with things like map
.
Python tuple
→ Go … nothing
Welcome, but there is not a built-in immutable data structure in Go. Come back later!
Go has if
package main
import "fmt"
func main() {
x := 10
if x > 0 {
fmt.Println("x is positive")
} else if x == 0 {
fmt.Println("x is zero")
} else {
fmt.Println("x is negative")
}
}
Go has for
, and kind has “while”
There is not a while
keyword in Go but you can use for
as a while
loop.
After all, for
and while
are equivalent in terms of functionalities.
package main
import "fmt"
func main() {
/////////////////////////////////////////////////////////////////
sum := 0
// a full size `for`
for i := 0; i < 10; i++ {
sum += i
}
fmt.Println(sum)
// you can only have the middle condition part, which makes it a while loop
for sum < 1000 {
sum += sum
}
/////////////////////////////////////////////////////////////////
}
Go has break
and continue
They work the exactly same in Python, Go, and C
Python match
→ Go switch
An example code from the official tutorial.
package main
import (
"fmt"
"runtime"
)
func main() {
fmt.Print("Go runs on ")
switch os := runtime.GOOS; os {
case "darwin":
fmt.Println("OS X.")
case "linux":
fmt.Println("Linux.")
default:
// freebsd, openbsd,
// plan9, windows...
fmt.Printf("%s.\\n", os)
}
}
Python def
→ Go func
In Go, there has to be a main
package and a main
function.
A function has to declare the type of the return value.
Python class
→ Go struct
and func
In OOP (Object-Oriented Programming), a class
is “data + functions on data”.
That’s why in Python, there are attributes and methods capsuled in a class.
In Go, the data part and the methods part are separated.
You need to first define a struct
which contains only the data fields.
Then you define some functions that bind to the struct
.
Look at the following example from the official tutorial.
package main
import (
"fmt"
"math"
)
// The data part
type Vertex struct {
X, Y float64
}
// a function that binds to the Vertex struct.
// It's a method of struct Vertex
func (v *Vertex) Scale(f float64) {
v.X = v.X * f
v.Y = v.Y * f
}
// It's another method of struct Vertex
func (v *Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
func main() {
v := &Vertex{3, 4}
fmt.Printf("Before scaling: %+v, Abs: %v\\n", v, v.Abs())
v.Scale(5)
fmt.Printf("After scaling: %+v, Abs: %v\\n", v, v.Abs())
}
Interesting, isn’t it?
The End
That’s about it! I know I didn’t include many AMAZING features of Go like goroutine
. They are beyond the purpose of this article and I’ll introduce them later!