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.
Go has a shorthand variable declaration wherein you can omit the types if the value is known at compile time.
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.
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.
If we typecast, the above will work:
Loops
Go just has a for
loop which has variations that match other looping primitives.
while
loop
Classic for
loop
do...while
loop
This doesn’t exist
for...of
loop
Strings
JavaScript | Golang |
---|---|
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.