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.
But don't worry, I'll provide it in text for those who like blog posts.
Control Flow
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")
}
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")
}
Conversions
There's no int()
or str()
, but here are a few ways of going about it. Personally, when going to string, I tend to use Sprintf
golang bytes array to string
s := string([]byte{65, 66, 67, 226, 130, 172})
fmt.Println(s)
golang bool to string
var b bool = true
fmt.Println(reflect.TypeOf(b))
strconv
var S string = strconv.FormatBool(true)
fmt.Println(reflect.TypeOf(S))
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)
golang 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
}
}
golang Print a Struct
Thankfully there's 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
}
Print without fields
fmt.Printf("%v", emp) // {Toul 24 500000}
Print with fields
fmt.Printf("%+v", emp) // {name:Toul age:24 salary:500000}
Conclusion
Hopefully, these help you on your GoLang journey!
Top comments (1)
see:
fmt.Printf("%#v", emp)