Core Primitives

Declaring variables

Go variables are declared with the var keyword which is NOT the same as var in JavaScript. Just forget the JS behavior when using var in Go. If variables are declared without a value, a default value for the type is assigned. For most custom types, this value would be nil which is like null in JS.

var i int          // i == 0
var i float32      // i == 0.0
var s string       // s == ""
var mySlice []int  // mySlice == nil

Go has a shorthand variable declaration wherein you can omit the types if the value is known at compile time.

i := 2
s := "sangeeth.dev"
f := float32(3.14)

const can be used instead of var if the value is static and can be computed at compile time. This is once again not the same thing as const in JS. Type is mandatory in this case.

const DAY_MS int = 24 * 60 * 60 * 1000;

Can’t mix numeric types together in an expression. Must explicitly convert one type to the other, even if the LHS variable’s type can hold the result.

var i int32 = 1
var j int64 = 2
fmt.Println(i + j) // ERROR!

If we typecast, the above will work:

var i int32 = 1
var j int64 = 2
fmt.Println(int64(i) + j) // ERROR!

Loops

Go just has a for loop which has variations that match other looping primitives.

while loop

i := 0
for i < 10 {
  fmt.Println(i)
  i++
}

Classic for loop

for i := 0; i < 10; i++ {
  fmt.Println(i)
}

do...while loop

This doesn’t exist

for...of loop

for i, val := range someSlice {
  fmt.Printf("index = %v, value = %v\n", i, val)
}

Strings

JavaScriptGolang
val.trim()strings.Trim(s, " ")
val.trimLeft()strings.TrimLeft(s, " ")

Public vs Private

Package (equivalent to JS modules) exports that are available to other modules (i.e public) must begin with a capital letter. Hence you have stuff like strings.Trim() with a capital T.

Go user types (like class in JS) can expose its members (like properties and methods) by also making them start with a capital letter.