Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
G

golang-for-nodejs-developers

> 开发工具
Open source

Examples of Golang compared to Node.js for learning By @miguelmota

4.8K stars0 likes1 views
WebsiteGitHub

About

Examples of Golang compared to Node.js for learning By @miguelmota





Golang for Node.js Developers

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.

Contents

  • Examples
    • comments

    • printing

    • logging

    • variables

    • types

      • bool
      • number
      • string
      • array
      • object
      • function
    • type check

    • interpolation

    • if/else

      • ternary
    • for

    • while

    • switch

    • arrays

      • slicing
      • copying
      • appending
      • prepending
    • uint8 arrays

    • array iteration

      • looping
      • mapping
      • filtering
      • reducing
      • sorting
    • buffers

      • allocate
      • big endian
      • little endian
      • hex
      • compare
      • equals
    • maps

      • iteration
    • objects

    • functions

    • default values

    • destructuring

    • spread operator

    • rest operator

    • swapping

    • classes

      • constructors
      • instantiation
      • "this"
    • generators

    • datetime

      • parsing
      • formatting
      • unix timestamp
    • timeout

    • interval

    • IIFE

    • files

      • creating
      • opening
      • writing
      • reading
      • closing
      • deleting
      • file descriptors
    • json

      • parse
      • stringify
    • big numbers

      • uint
      • string
      • hex
      • buffers
      • compare
      • equals
    • promises

      • then
      • all
    • async/await

    • streams

      • reading
      • writing
    • event emitter

    • errors

    • try/catch

    • exceptions

    • regex

    • exec (sync)

    • exec (async)

    • tcp server

    • udp server

    • http server

    • url parse

    • gzip

      • compress
      • decompress
    • dns

      • ns lookup
      • ip lookup
      • mx lookup
      • txt lookup
      • set resolution servers
    • crypto

      • sha256
    • env vars

    • cli args

    • cli flags

    • stdout

    • stderr

    • stdin

    • modules

      • installing
      • updating
      • removing
      • importing
      • exporting
      • publishing
    • stack trace

    • databases

      • sqlite3
    • testing

    • benchmarking

    • documentation

  • Contributing
  • License

Examples

All sample code is available in examples/

comments


Node.js

node
// this is a line comment

/*
 this is a block comment
*/

Go

go
package main

func main() {
	// this is a line comment

	/*
	   this is a block comment
	*/
}

⬆ back to top

printing


Node.js

node
console.log('print to stdout')
console.log('format %s %d', 'example', 1)
console.error('print to stderr')

Output

bash
print to stdout
format example 1
print to stderr

Go

go
package 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

bash
print to stdout
format example 1
print to stderr

⬆ back to top

logging


Node.js

node
console.log((new Date()).toISOString(), 'hello world')

Output

bash
2021-04-11T20:55:07.451Z hello world

Go

go
package main

import "log"

func main() {
	log.Println("hello world")
}

Output

bash
2021/04/11 13:55:07 hello world

(Package log writes to standard error ánd prints the date and time of each logged message)

⬆ back to top

variables


Node.js

node
// function scoped
var foo = 'foo'

// block scoped
let bar = 'bar'

// constant
const qux = 'qux'

Go

(variables are block scoped in Go)

go
package main

func main() {
	// explicit
	var foo string = "foo"

	// type inferred
	var bar = "foo"

	// shorthand
	baz := "bar"

	// constant
	const qux = "qux"
}

⬆ back to top

interpolation


Node.js

node
const name = 'bob'
const age = 21
const message = `${name} is ${age} years old`

console.log(message)

Output

bash
bob is 21 years old

Go

go
package main

import "fmt"

func main() {
	name := "bob"
	age := 21
	message := fmt.Sprintf("%s is %d years old", name, age)

	fmt.Println(message)
}

Output

bash
bob is 21 years old

⬆ back to top

types


Node.js

node
// 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 {}

Go

…

⬆ back to top

type check


Node.js

node
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

bash
boolean
number
string
symbol
null
undefined
number
object
array
function
error
date
regexp
map
set
promise
generatorfunction
function

Go

go
package 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

bash
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.Regexp

⬆ back to top

if/else


Node.js

node
const 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

bash
array exists
length is 2
no

Go

go
package 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

bash
array exists
length is 2
no

⬆ back to top

for


Node.js

node
for (let i = 0; i <= 5; i++) {
  console.log(i)
}

Output

bash
0
1
2
3
4
5

Go

go
package main

import "fmt"

func main() {
	for i := 0; i <= 5; i++ {
		fmt.Println(i)
	}
}

Output

bash
0
1
2
3
4
5

⬆ back to top

while


Node.js

node
let i = 0

while (i <= 5) {
  console.log(i)

  i++
}

Output

bash
0
1
2
3
4
5

Go

(there's no while keyword in Go but the same functionality is achieved by using for)

go
package main

import "fmt"

func main() {
	i := 0

	for i <= 5 {
		fmt.Println(i)

		i++
	}
}

Output

bash
0
1
2
3
4
5

⬆ back to top

switch


Node.js

node
const 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

bash
B
B - falling through
C - falling through
second default

Go

go
package 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

bash
B
B - falling through
C - falling through
second default

⬆ back to top

arrays


Examples of slicing, copying, appending, and prepending arrays.

Node.js

node
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

bash
[ 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 ]

Go

go
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

bash
[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]

⬆ back to top

uint8 arrays


Node.js

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Godemoexamplesgogolang

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category开发工具
PricingOpen source

> Related tools

V
VS Code
流行的开源代码编辑器
G
Git
分布式版本控制系统
V
Vite
下一代前端构建工具