Examples of Golang compared to Node.js for learning By @miguelmota
Examples of Golang compared to Node.js for learning By @miguelmota
Examples of Golang examples compared to Node.js for learning This guide full of examples is intended for people learning Go that are coming from Node.js, although the vice versa can work too. This is not meant to be a complete guide and it is assumed that you've gone through the Tour of Go tutorial. This guide is meant to be barely good enough to help you at a high level understand how to do X in Y and doing further learning on your own is of course required.
All sample code is available in examples/
// this is a line comment
/*
this is a block comment
*/package main
func main() {
// this is a line comment
/*
this is a block comment
*/
}console.log('print to stdout')
console.log('format %s %d', 'example', 1)
console.error('print to stderr')Output
print to stdout
format example 1
print to stderrpackage main
import (
"fmt"
"os"
)
func main() {
fmt.Println("print to stdout")
fmt.Printf("format %s %v\n", "example", 1)
fmt.Fprintf(os.Stderr, "print to stderr")
}Output
print to stdout
format example 1
print to stderrconsole.log((new Date()).toISOString(), 'hello world')Output
2021-04-11T20:55:07.451Z hello worldpackage main
import "log"
func main() {
log.Println("hello world")
}Output
2021/04/11 13:55:07 hello world(Package log writes to standard error ánd prints the date and time of each logged message)
// function scoped
var foo = 'foo'
// block scoped
let bar = 'bar'
// constant
const qux = 'qux'(variables are block scoped in Go)
package main
func main() {
// explicit
var foo string = "foo"
// type inferred
var bar = "foo"
// shorthand
baz := "bar"
// constant
const qux = "qux"
}const name = 'bob'
const age = 21
const message = `${name} is ${age} years old`
console.log(message)Output
bob is 21 years oldpackage main
import "fmt"
func main() {
name := "bob"
age := 21
message := fmt.Sprintf("%s is %d years old", name, age)
fmt.Println(message)
}Output
bob is 21 years old// primitives
const myBool = true
const myNumber = 10
const myString = 'foo'
const mySymbol = Symbol('bar')
const myNull = null
const myUndefined = undefined
// object types
const myObject = {}
const myArray = []
const myFunction = function() {}
const myError = new Error('error')
const myDate = new Date()
const myRegex = /a/
const myMap = new Map()
const mySet = new Set()
const myPromise = Promise.resolve()
const myGenerator = function *() {}
const myClass = class {}…function typeOf(obj) {
return {}.toString.call(obj).split(' ')[1].slice(0,-1).toLowerCase()
}
const values = [
true,
10,
'foo',
Symbol('bar'),
null,
undefined,
NaN,
{},
[],
function(){},
new Error(),
new Date(),
/a/,
new Map(),
new Set(),
Promise.resolve(),
function *() {},
class {},
]
for (value of values) {
console.log(typeOf(value))
}Output
boolean
number
string
symbol
null
undefined
number
object
array
function
error
date
regexp
map
set
promise
generatorfunction
functionpackage main
import (
"fmt"
"reflect"
"regexp"
"time"
)
func main() {
values := []interface{}{
true,
int8(10),
int16(10),
int32(10),
int64(10),
uint(10),
uint8(10),
uint16(10),
uint32(10),
uint64(10),
uintptr(10),
float32(10.5),
float64(10.5),
complex64(-1 + 10i),
complex128(-1 + 10i),
"foo",
byte(10),
'a',
rune('a'),
struct{}{},
[]string{},
map[string]int{},
func() {},
make(chan bool),
nil,
new(int),
time.Now(),
regexp.MustCompile(`^a$`),
}
for _, value := range values {
fmt.Println(reflect.TypeOf(value))
}
}Output
bool
int8
int16
int32
int64
uint
uint8
uint16
uint32
uint64
uintptr
float32
float64
complex64
complex128
string
uint8
int32
int32
struct {}
[]string
map[string]int
func()
chan bool
<nil>
*int
time.Time
*regexp.Regexpconst array = [1, 2]
if (array) {
console.log('array exists')
}
if (array.length === 2) {
console.log('length is 2')
} else if (array.length === 1) {
console.log('length is 1')
} else {
console.log('length is other')
}
const isOddLength = array.length % 2 == 1 ? 'yes' : 'no'
console.log(isOddLength)Output
array exists
length is 2
nopackage main
import "fmt"
func main() {
array := []byte{1, 2}
if array != nil {
fmt.Println("array exists")
}
if len(array) == 2 {
fmt.Println("length is 2")
} else if len(array) == 1 {
fmt.Println("length is 1")
} else {
fmt.Println("length is other")
}
// closest thing to ternary operator
isOddLength := "no"
if len(array)%2 == 1 {
isOddLength = "yes"
}
fmt.Println(isOddLength)
}Output
array exists
length is 2
nofor (let i = 0; i <= 5; i++) {
console.log(i)
}Output
0
1
2
3
4
5package main
import "fmt"
func main() {
for i := 0; i <= 5; i++ {
fmt.Println(i)
}
}Output
0
1
2
3
4
5let i = 0
while (i <= 5) {
console.log(i)
i++
}Output
0
1
2
3
4
5(there's no while keyword in Go but the same functionality is achieved by using for)
package main
import "fmt"
func main() {
i := 0
for i <= 5 {
fmt.Println(i)
i++
}
}Output
0
1
2
3
4
5const value = 'b'
switch(value) {
case 'a':
console.log('A')
break
case 'b':
console.log('B')
break
case 'c':
console.log('C')
break
default:
console.log('first default')
}
switch(value) {
case 'a':
console.log('A - falling through')
case 'b':
console.log('B - falling through')
case 'c':
console.log('C - falling through')
default:
console.log('second default')
}Output
B
B - falling through
C - falling through
second defaultpackage main
import "fmt"
func main() {
value := "b"
switch value {
case "a":
fmt.Println("A")
case "b":
fmt.Println("B")
case "c":
fmt.Println("C")
default:
fmt.Println("first default")
}
switch value {
case "a":
fmt.Println("A - falling through")
fallthrough
case "b":
fmt.Println("B - falling through")
fallthrough
case "c":
fmt.Println("C - falling through")
fallthrough
default:
fmt.Println("second default")
}
}Output
B
B - falling through
C - falling through
second defaultExamples of slicing, copying, appending, and prepending arrays.
const array = [1, 2, 3, 4, 5]
console.log(array)
const clone = array.slice(0)
console.log(clone)
const sub = array.slice(2,4)
console.log(sub)
const concatenated = clone.concat([6, 7])
console.log(concatenated)
const prepended = [-2,-1,0].concat(concatenated)
console.log(prepended)Output
[ 1, 2, 3, 4, 5 ]
[ 1, 2, 3, 4, 5 ]
[ 3, 4 ]
[ 1, 2, 3, 4, 5, 6, 7 ]
[ -2, -1, 0, 1, 2, 3, 4, 5, 6, 7 ]package main
import "fmt"
func main() {
array := []int{1, 2, 3, 4, 5}
fmt.Println(array)
clone := make([]int, len(array))
copy(clone, array)
fmt.Println(clone)
sub := array[2:4]
fmt.Println(sub)
concatenated := append(array, []int{6, 7}...)
fmt.Println(concatenated)
prepended := append([]int{-2, -1, 0}, concatenated...)
fmt.Println(prepended)
}Output
[1 2 3 4 5]
[1 2 3 4 5]
[3 4]
[1 2 3 4 5 6 7]
[-2 -1 0 1 2 3 4 5 6 7]No open issues yet, or sync has not completed.