A Journey from JavaScript into GoLang - Day 1
4 min readAug 8, 2016
Today I learn GoLang. Hopefully you find this run-through useful in getting acquainted.
Some resources I have accumulated are:
- docIntro := https://golang.org/doc/code.html
- bookIntro := https://www.golang-book.com/books/intro
- videoOverview := https://www.youtube.com/watch?v=rKnDgT73v8s
- slidesOverview := https://talks.golang.org/2016/applicative.slide
- articleIntro := https://medium.com/@mandrigin/learning-go-golang-47127a796323#.1godq4k4g
Takeaways:
So far, GoLang is similar to Javascript with some exceptions:
- Static typing
- Manual type-conversion
- Manual management of array/slice lengths
- For loop has an option to operate like Lodash each
- Documentation can be retrieved from terminal
Program Interface:
- Package Declaration — specifies library to use at beginning of program
package main
- Import Statement — imports code from other packages
import “fmt”
- Function Declarations — building blocks of GoLang code, comprised of inputs, outputs, and ordered steps (statements).
func main() {
fmt.Println(“Hello World”)
}
- Statements — building blocks of a function, comprised of primitive declarations, functions, and invocations
// Println function from fmt library
// invoked
// with new primitive "Hello World"fmt.Println(“Hello World”
- Documentation — GoLang is well documented, and documentation can be retrieved straight from terminal
godoc fmt Println // Returns snippet about fmt's Println function
Numbers:
- Signed Integers — whole — positive, negative, or zero — rune=int32
- Unsigned Integers — whole — positive or zero (no +/- sign) — byte=uint8
- Floating Numbers — decimal — use float64 as default
Strings:
- String Literals — “ ” or ` ` — declares a new string
- String Methods — String type shares properties like length, indexing, concatenation, etc..
func main() {
fmt.Println(len(“Hello World”)) // Length
fmt.Println(“Hello World”[7]) // Index 7 from 0
fmt.Println(“Hello” + “World”) // Concatenation
fmt.Println(`Hello
World`) // Includes newline
}
Booleans:
- Operators — && — AND, || — OR, ! — NOT
Variables:
- Declaration and assignment — use either “var” or “:”
- Type — variables are typed and type can be inferred
// Both of these statements do the same thing:
var x string = “Hello World”
x := "Hello World"
Scope:
- Lexical Scoping — variables are scoped to the block they are defined in
// We need to define the "x" variable outside of the functions if we want both functions to have access to it
var x string = “Hello World”
func main() {
fmt.Println(x)
}
func f() {
fmt.Println(x)
}
Constants:
- These are basically variables whose values cannot be changed
// This would throw an error
const x string = "Hello World"
x = "Some other string"
Comparison:
- Equals — “==” is hard comparison with no type conversion
- Greater or equal / Lesser or equal — “>=” / “<=”
Loops:
- For loop — The only kind of loop in GoLang — takes a conditional — looks similar to JS for loop
//Prints numbers 1 through 10 on different lines
func main() {
for i := 1; i <= 10; i++ {
fmt.Println(i)
}
}
- Alternative syntax — “range x” is same as “for entirety of x” — “value” is same as x[i] — “_” is saying we don’t have use for an index variable
var total float64 = 0
for _, value := range x {
total += value
}
fmt.Println(total / float64(len(x)))
If / Else:
if i % 2 == 0 {
fmt.Println(i, “even”)
} else {
fmt.Println(i, “odd”)
}
Switch:
switch i {
case 0: fmt.Println("Zero")
case 1: fmt.Println("One")
case 2: fmt.Println("Two")
case 3: fmt.Println("Three")
case 4: fmt.Println("Four")
case 5: fmt.Println("Five")
default: fmt.Println("Unknown Number")
}
Arrays:
- Arrays require a specified length
// Option 1:
var x [5]int
x[0] = 98
x[1] = 93
x[2] = 77
x[3] = 82
x[4] = 83// Option 2:
x := [5]float64{ 98, 93, 77, 82, 83 }// Option 3:
x := [5]float64{
98,
93,
77,
82,
83,
}
Type Conversion:
- There is no auto-type-conversion, so the following will throw an error:
// This will throw an error because len(x) returns an integer
// Thus, we have fmt.Println(float64 / integer)var total float64 = 0
for i := 0; i < len(x); i++ {
total += x[i]
}
fmt.Println(total / len(x))
- Convert type manually — use the type name as a function
var total float64 = 0
for i := 0; i < len(x); i++ {
total += x[i]
}
fmt.Println(total / float64(len(x)))
Slices:
- A slice is an array with a max size, but no fixed or min size
func main() {
// Create slice(max=3) that contains [1,2,3]
slice1 := []int{1,2,3}
// Create slice(max=6) that contains slice1 with [4,5,6] appended
slice2 := append(slice1, 4, 5, 6)
// Create slice(max=2) that contains []
slice3 := make([]int, 2)
// Copy to slice3, slice2 from index 3 to end ([4,5,6])
// This results in [4,5] because of slice3's size max=2
copy(slice3, slice2[3:])
fmt.Println(slice1, slice2, slice3) // [1,2,3][1,2,3,4,5,6][4,5]
// Copy to slice1, slice3. This overwrites slice1's index 0 and 1
copy(slice1, slice3)
fmt.Println(slice1, slice2, slice3) // [4,5,3][1,2,3,4,5,6][4,5]
}
Maps:
- Maps are like hash-tables, but key and value types are required.
func main() {
elements := map[string]map[string]string{
"H": map[string]string{
"name":"Hydrogen", "state":"gas",
},
"He": map[string]string{
"name":"Helium", "state":"gas",
},
"Li": map[string]string{
"name":"Lithium", "state":"solid",
},
}
}