Ultimate GoLang Beginner's Cheat Sheet

Ultimate GoLang Beginner's Cheat Sheet

golang

When I first learned GoLang 5 years ago, I remember constantly looking up its syntax and things like printing, which was much different than Python 3's way of doing things.

So, I've put together the things I looked up the most during my first few months with GoLang in a handy cheat sheet.

Ultimate-Beginners-cheat-sheet

But don't worry, I'll provide it in text for those who like blog posts.

1. Control Flow

golang switch

The GoLang switch is a little different in that it must always have a 'default' value.

t := time.Now()
switch {
case t.Hour() < 12:
   fmt.Println("It's before twelve")
default:
   fmt.Println("It's after twelve")
}

golang else if

There's no elif here like in Python, you have to write it out.

// else if
if num := 0; num < 0 {
   fmt.Println(num, "is negative")
} else if num < 10 {
   fmt.Printf("%d has one digit", num)
} else {
   fmt.Println(num, "has multiple digits")
}

2. Conversions

There's no int() , str() here like in Python 3.

golang bytes array to string

s := string([]byte{65, 66, 67, 226, 130, 172})
fmt.Println(s)

golang bool to string

There are several ways to do this depending on your situation. Personally, I usually go with Sprintf.

to terminal

var b bool = true
fmt.Println(reflect.TypeOf(b))

with strconv

var S string = strconv.FormatBool(true)
fmt.Println(reflect.TypeOf(S))

with Sprintf

B := true
str := fmt.Sprintf("%v", B)
fmt.Println(str)
fmt.Println(reflect.TypeOf(s))

golang string to int

strVar := "100"
intVar, err := strconv.Atoi(strVar)
fmt.Println(intVar, err, reflect.TypeOf(intVar))

int to string

i := 10
s1 := strconv.FormatInt(int64(i), 10)
s2 := strconv.Itoa(i)
fmt.Printf("%v, %v\n", s1, s2)

3. while Loops

In GoLang there is no while keyword, only for, so to emulate the behavior of while-loops, here's how it is done.

Like a for loop

// while
i := 0
for i < 10 {
   // ...
}

Endless loop

// Endless while loop
for {
   // ...
}

While true

// while true
for true {
   // ...
}

do-while

// do-while
for {
   if !condition {
      break
   }
}

4. golang Print a Struct

Thankfully there are built-in struct printing from the standard library.

// Printing struct
type employee struct {
   name   string
   age    int
   salary int
}
emp := &employee{
   name:   "Toul",
   age:    24,
   salary: 500000, // a writer can dream
}
fmt.Printf("%v", emp)  // {Toul 24 500000}
fmt.Printf("%+v", emp) // {name:Toul age:24 salary:500000}


Comments

Sign up or Sign in to join the conversation.