{"id":13400505,"url":"https://github.com/miguelmota/golang-for-nodejs-developers","last_synced_at":"2025-05-14T13:09:32.314Z","repository":{"id":37664038,"uuid":"163927392","full_name":"miguelmota/golang-for-nodejs-developers","owner":"miguelmota","description":"Examples of Golang compared to Node.js for learning 🤓","archived":false,"fork":false,"pushed_at":"2023-02-02T11:21:08.000Z","size":231,"stargazers_count":4705,"open_issues_count":1,"forks_count":525,"subscribers_count":51,"default_branch":"master","last_synced_at":"2025-04-11T06:12:53.482Z","etag":null,"topics":["demo","examples","go","golang","guide","howto","javascript","learning","nodejs","reference","tutorial"],"latest_commit_sha":null,"homepage":"https://github.com/miguelmota/golang-for-nodejs-developers","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/miguelmota.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null},"funding":{"github":["miguelmota"],"patreon":"miguelmota"}},"created_at":"2019-01-03T05:30:44.000Z","updated_at":"2025-04-06T16:35:54.000Z","dependencies_parsed_at":"2023-02-17T19:01:15.604Z","dependency_job_id":null,"html_url":"https://github.com/miguelmota/golang-for-nodejs-developers","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/miguelmota%2Fgolang-for-nodejs-developers","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/miguelmota%2Fgolang-for-nodejs-developers/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/miguelmota%2Fgolang-for-nodejs-developers/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/miguelmota%2Fgolang-for-nodejs-developers/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/miguelmota","download_url":"https://codeload.github.com/miguelmota/golang-for-nodejs-developers/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254149976,"owners_count":22022852,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["demo","examples","go","golang","guide","howto","javascript","learning","nodejs","reference","tutorial"],"created_at":"2024-07-30T19:00:52.752Z","updated_at":"2025-05-14T13:09:27.289Z","avatar_url":"https://github.com/miguelmota.png","language":"Go","funding_links":["https://github.com/sponsors/miguelmota","https://patreon.com/miguelmota"],"categories":["Go","网站","Websites","Repositories","Programming languages","Tutorials","Tooling"],"sub_categories":["教程","Tutorials","Go","🎥 YouTube \u0026 Video Content"],"readme":"\u003ch3 align=\"center\"\u003e\n  \u003cbr /\u003e\n  \u003cimg src=\"https://user-images.githubusercontent.com/168240/114315374-8ff5b480-9ab3-11eb-8323-b83858e8e74f.png\" alt=\"logo\" width=\"800\" /\u003e\n  \u003cbr /\u003e\n  \u003cbr /\u003e\n  \u003cbr /\u003e\n\u003c/h3\u003e\n\n# Golang for Node.js Developers\n\n\u003e Examples of [Golang](https://golang.org/) examples compared to [Node.js](https://nodejs.org/) for learning\n\n[![License](http://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/miguelmota/golang-for-nodejs-developers/master/LICENSE)\n[![Mentioned in Awesome Go](https://awesome.re/mentioned-badge.svg)](https://github.com/avelino/awesome-go)\n[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](#contributing)\n\nThis 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](https://tour.golang.org/) 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.\n\n## Contents\n\n- [Examples](#examples)\n  - [comments](#comments)\n  - [printing](#printing)\n  - [logging](#logging)\n  - [variables](#variables)\n  - [types](#types)\n    - [bool](#types)\n    - [number](#types)\n    - [string](#types)\n    - [array](#types)\n    - [object](#types)\n    - [function](#types)\n  - [type check](#type-check)\n  - [interpolation](#interpolation)\n  - [if/else](#ifelse)\n    - [ternary](#ifelse)\n  - [for](#for)\n  - [while](#while)\n  - [switch](#switch)\n  - [arrays](#arrays)\n    - [slicing](#arrays)\n    - [copying](#arrays)\n    - [appending](#arrays)\n    - [prepending](#arrays)\n  - [uint8 arrays](#uint8-arrays)\n  - [array iteration](#array-iteration)\n    - [looping](#array-iteration)\n    - [mapping](#array-iteration)\n    - [filtering](#array-iteration)\n    - [reducing](#array-iteration)\n\t- [sorting](#array-sorting)\n  - [buffers](#buffers)\n    - [allocate](#buffers)\n    - [big endian](#buffers)\n    - [little endian](#buffers)\n    - [hex](#buffers)\n    - [compare](#buffers)\n    - [equals](#buffers)\n  - [maps](#maps)\n    - [iteration](#maps)\n  - [objects](#objects)\n  - [functions](#functions)\n  - [default values](#default-values)\n  - [destructuring](#destructuring)\n  - [spread operator](#spread-operator)\n  - [rest operator](#rest-operator)\n  - [swapping](#swapping)\n  - [classes](#classes)\n    - [constructors](#classes)\n    - [instantiation](#classes)\n    - [\"this\"](#classes)\n  - [generators](#generators)\n  - [datetime](#datetime)\n    - [parsing](#datetime)\n    - [formatting](#datetime)\n    - [unix timestamp](#datetime)\n  - [timeout](#timeout)\n  - [interval](#interval)\n  - [IIFE](#iife)\n  - [files](#files)\n    - [creating](#files)\n    - [opening](#files)\n    - [writing](#files)\n    - [reading](#files)\n    - [closing](#files)\n    - [deleting](#files)\n    - [file descriptors](#files)\n  - [json](#json)\n    - [parse](#json)\n    - [stringify](#json)\n  - [big numbers](#big-numbers)\n    - [uint](#big-numbers)\n    - [string](#big-numbers)\n    - [hex](#big-numbers)\n    - [buffers](#big-numbers)\n    - [compare](#buffers)\n    - [equals](#buffers)\n  - [promises](#promises)\n    - [then](#promises)\n    - [all](#promises)\n  - [async/await](#async-await)\n  - [streams](#streams)\n    - [reading](#streams)\n    - [writing](#streams)\n  - [event emitter](#event-emitter)\n  \u003c!--\n    - [transform](#streams)\n  - [concurrency](#concurrency)\n    - [threads](#concurrency)\n    - [forking](#concurrency)\n  - [message passing](#message-passing)\n  - [first-class functions](#first-class-functions)\n  --\u003e\n  - [errors](#errors)\n  - [try/catch](#trycatch)\n  - [exceptions](#exceptions)\n  - [regex](#regex)\n  - [exec (sync)](#exec-sync)\n  - [exec (async)](#exec-async)\n  - [tcp server](#tcp-server)\n  - [udp server](#udp-server)\n  - [http server](#http-server)\n  - [url parse](#url-parse)\n  - [gzip](#gzip)\n    - [compress](#gzip)\n    - [decompress](#gzip)\n  - [dns](#dns)\n    - [ns lookup](#dns)\n    - [ip lookup](#dns)\n    - [mx lookup](#dns)\n    - [txt lookup](#dns)\n    - [set resolution servers](#dns)\n  - [crypto](#crypto)\n    - [sha256](#crypto)\n  - [env vars](#env-vars)\n  - [cli args](#cli-args)\n  - [cli flags](#cli-flags)\n  - [stdout](#stdout)\n  - [stderr](#stderr)\n  - [stdin](#stdin)\n  - [modules](#modules)\n    - [installing](#modules)\n    - [updating](#modules)\n    - [removing](#modules)\n    - [importing](#modules)\n    - [exporting](#modules)\n    - [publishing](#modules)\n  - [stack trace](#stack-trace)\n  - [databases](#databases)\n    - [sqlite3](#databases)\n  - [testing](#testing)\n  - [benchmarking](#benchmarking)\n  - [documentation](#documentation)\n- [Contributing](#contributing)\n- [License](#license)\n\n## Examples\n\nAll sample code is available in [examples/](examples/)\n\n### comments\n---\n\n#### Node.js\n\n```node\n// this is a line comment\n\n/*\n this is a block comment\n*/\n```\n\n#### Go\n\n```go\npackage main\n\nfunc main() {\n\t// this is a line comment\n\n\t/*\n\t   this is a block comment\n\t*/\n}\n```\n\n**[⬆ back to top](#contents)**\n\n### printing\n---\n\n#### Node.js\n\n```node\nconsole.log('print to stdout')\nconsole.log('format %s %d', 'example', 1)\nconsole.error('print to stderr')\n```\n\nOutput\n\n```bash\nprint to stdout\nformat example 1\nprint to stderr\n```\n\n#### Go\n\n```go\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tfmt.Println(\"print to stdout\")\n\tfmt.Printf(\"format %s %v\\n\", \"example\", 1)\n\tfmt.Fprintf(os.Stderr, \"print to stderr\")\n}\n```\n\nOutput\n\n```bash\nprint to stdout\nformat example 1\nprint to stderr\n```\n\n**[⬆ back to top](#contents)**\n\n### logging\n---\n\n#### Node.js\n\n```node\nconsole.log((new Date()).toISOString(), 'hello world')\n```\n\nOutput\n\n```bash\n2021-04-11T20:55:07.451Z hello world\n```\n\n#### Go\n\n```go\npackage main\n\nimport \"log\"\n\nfunc main() {\n\tlog.Println(\"hello world\")\n}\n```\n\nOutput\n\n```bash\n2021/04/11 13:55:07 hello world\n```\n\n_(Package `log` writes to standard error ánd prints the date and time of each logged message)_\n\n**[⬆ back to top](#contents)**\n\n### variables\n---\n\n#### Node.js\n\n```node\n// function scoped\nvar foo = 'foo'\n\n// block scoped\nlet bar = 'bar'\n\n// constant\nconst qux = 'qux'\n```\n\n#### Go\n\n(variables are block scoped in Go)\n\n```go\npackage main\n\nfunc main() {\n\t// explicit\n\tvar foo string = \"foo\"\n\n\t// type inferred\n\tvar bar = \"foo\"\n\n\t// shorthand\n\tbaz := \"bar\"\n\n\t// constant\n\tconst qux = \"qux\"\n}\n```\n\n**[⬆ back to top](#contents)**\n\n### interpolation\n---\n\n#### Node.js\n\n```node\nconst name = 'bob'\nconst age = 21\nconst message = `${name} is ${age} years old`\n\nconsole.log(message)\n```\n\nOutput\n\n```bash\nbob is 21 years old\n```\n\n#### Go\n\n```go\npackage main\n\nimport \"fmt\"\n\nfunc main() {\n\tname := \"bob\"\n\tage := 21\n\tmessage := fmt.Sprintf(\"%s is %d years old\", name, age)\n\n\tfmt.Println(message)\n}\n```\n\nOutput\n\n```bash\nbob is 21 years old\n```\n\n**[⬆ back to top](#contents)**\n\n### types\n---\n\n#### Node.js\n\n```node\n// primitives\nconst myBool = true\nconst myNumber = 10\nconst myString = 'foo'\nconst mySymbol = Symbol('bar')\nconst myNull = null\nconst myUndefined = undefined\n\n// object types\nconst myObject = {}\nconst myArray = []\nconst myFunction = function() {}\nconst myError = new Error('error')\nconst myDate = new Date()\nconst myRegex = /a/\nconst myMap = new Map()\nconst mySet = new Set()\nconst myPromise = Promise.resolve()\nconst myGenerator = function *() {}\nconst myClass = class {}\n```\n\n#### Go\n\n```go\npackage main\n\nfunc main() {\n\t// primitives\n\tvar myBool bool = true\n\tvar myInt int = 10\n\tvar myInt8 int8 = 10\n\tvar myInt16 int16 = 10\n\tvar myInt32 int32 = 10\n\tvar myInt64 int64 = 10\n\tvar myUint uint = 10\n\tvar myUint8 uint8 = 10\n\tvar myUint16 uint16 = 10\n\tvar myUint32 uint32 = 10\n\tvar myUint64 uint64 = 10\n\tvar myUintptr uintptr = 10\n\tvar myFloat32 float32 = 10.5\n\tvar myFloat64 float64 = 10.5\n\tvar myComplex64 complex64 = -1 + 10i\n\tvar myComplex128 complex128 = -1 + 10i\n\tvar myString string = \"foo\"\n\tvar myByte byte = 10  // alias to uint8\n\tvar myRune rune = 'a' // alias to int32\n\n\t// composite types\n\tvar myStruct struct{} = struct{}{}\n\tvar myArray []string = []string{}\n\tvar myMap map[string]int = map[string]int{}\n\tvar myFunction func() = func() {}\n\tvar myChannel chan bool = make(chan bool)\n\tvar myInterface interface{} = nil\n\tvar myPointer *int = new(int)\n}\n```\n\n**[⬆ back to top](#contents)**\n\n### type check\n---\n\n#### Node.js\n\n```node\nfunction typeOf(obj) {\n  return {}.toString.call(obj).split(' ')[1].slice(0,-1).toLowerCase()\n}\n\nconst values = [\n  true,\n  10,\n  'foo',\n  Symbol('bar'),\n  null,\n  undefined,\n  NaN,\n  {},\n  [],\n  function(){},\n  new Error(),\n  new Date(),\n  /a/,\n  new Map(),\n  new Set(),\n  Promise.resolve(),\n  function *() {},\n  class {},\n]\n\nfor (value of values) {\n  console.log(typeOf(value))\n}\n```\n\nOutput\n\n```bash\nboolean\nnumber\nstring\nsymbol\nnull\nundefined\nnumber\nobject\narray\nfunction\nerror\ndate\nregexp\nmap\nset\npromise\ngeneratorfunction\nfunction\n```\n\n#### Go\n\n```go\npackage main\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\t\"regexp\"\n\t\"time\"\n)\n\nfunc main() {\n\tvalues := []interface{}{\n\t\ttrue,\n\t\tint8(10),\n\t\tint16(10),\n\t\tint32(10),\n\t\tint64(10),\n\t\tuint(10),\n\t\tuint8(10),\n\t\tuint16(10),\n\t\tuint32(10),\n\t\tuint64(10),\n\t\tuintptr(10),\n\t\tfloat32(10.5),\n\t\tfloat64(10.5),\n\t\tcomplex64(-1 + 10i),\n\t\tcomplex128(-1 + 10i),\n\t\t\"foo\",\n\t\tbyte(10),\n\t\t'a',\n\t\trune('a'),\n\t\tstruct{}{},\n\t\t[]string{},\n\t\tmap[string]int{},\n\t\tfunc() {},\n\t\tmake(chan bool),\n\t\tnil,\n\t\tnew(int),\n\t\ttime.Now(),\n\t\tregexp.MustCompile(`^a$`),\n\t}\n\n\tfor _, value := range values {\n\t\tfmt.Println(reflect.TypeOf(value))\n\t}\n}\n```\n\nOutput\n\n```bash\nbool\nint8\nint16\nint32\nint64\nuint\nuint8\nuint16\nuint32\nuint64\nuintptr\nfloat32\nfloat64\ncomplex64\ncomplex128\nstring\nuint8\nint32\nint32\nstruct {}\n[]string\nmap[string]int\nfunc()\nchan bool\n\u003cnil\u003e\n*int\ntime.Time\n*regexp.Regexp\n```\n\n**[⬆ back to top](#contents)**\n\n### if/else\n---\n\n#### Node.js\n\n```node\nconst array = [1, 2]\n\nif (array) {\n  console.log('array exists')\n}\n\nif (array.length === 2) {\n  console.log('length is 2')\n} else if (array.length === 1) {\n  console.log('length is 1')\n} else {\n  console.log('length is other')\n}\n\nconst isOddLength = array.length % 2 == 1 ? 'yes' : 'no'\n\nconsole.log(isOddLength)\n```\n\nOutput\n\n```bash\narray exists\nlength is 2\nno\n```\n\n#### Go\n\n```go\npackage main\n\nimport \"fmt\"\n\nfunc main() {\n\tarray := []byte{1, 2}\n\n\tif array != nil {\n\t\tfmt.Println(\"array exists\")\n\t}\n\n\tif len(array) == 2 {\n\t\tfmt.Println(\"length is 2\")\n\t} else if len(array) == 1 {\n\t\tfmt.Println(\"length is 1\")\n\t} else {\n\t\tfmt.Println(\"length is other\")\n\t}\n\n\t// closest thing to ternary operator\n\tisOddLength := \"no\"\n\tif len(array)%2 == 1 {\n\t\tisOddLength = \"yes\"\n\t}\n\n\tfmt.Println(isOddLength)\n}\n```\n\nOutput\n\n```bash\narray exists\nlength is 2\nno\n```\n\n**[⬆ back to top](#contents)**\n\n### for\n---\n\n#### Node.js\n\n```node\nfor (let i = 0; i \u003c= 5; i++) {\n  console.log(i)\n}\n```\n\nOutput\n\n```bash\n0\n1\n2\n3\n4\n5\n```\n\n#### Go\n\n```go\npackage main\n\nimport \"fmt\"\n\nfunc main() {\n\tfor i := 0; i \u003c= 5; i++ {\n\t\tfmt.Println(i)\n\t}\n}\n```\n\nOutput\n\n```bash\n0\n1\n2\n3\n4\n5\n```\n\n**[⬆ back to top](#contents)**\n\n### while\n---\n\n#### Node.js\n\n```node\nlet i = 0\n\nwhile (i \u003c= 5) {\n  console.log(i)\n\n  i++\n}\n```\n\nOutput\n\n```bash\n0\n1\n2\n3\n4\n5\n```\n\n#### Go\n\n(there's no *while* keyword in Go but the same functionality is achieved by using *for*)\n\n```go\npackage main\n\nimport \"fmt\"\n\nfunc main() {\n\ti := 0\n\n\tfor i \u003c= 5 {\n\t\tfmt.Println(i)\n\n\t\ti++\n\t}\n}\n```\n\nOutput\n\n```bash\n0\n1\n2\n3\n4\n5\n```\n\n**[⬆ back to top](#contents)**\n\n### switch\n---\n\n#### Node.js\n\n```node\nconst value = 'b'\n\nswitch(value) {\n  case 'a':\n    console.log('A')\n    break\n  case 'b':\n    console.log('B')\n    break\n  case 'c':\n    console.log('C')\n    break\n  default:\n    console.log('first default')\n}\n\nswitch(value) {\n  case 'a':\n    console.log('A - falling through')\n  case 'b':\n    console.log('B - falling through')\n  case 'c':\n    console.log('C - falling through')\n  default:\n    console.log('second default')\n}\n```\n\nOutput\n\n```bash\nB\nB - falling through\nC - falling through\nsecond default\n```\n\n#### Go\n\n```go\npackage main\n\nimport \"fmt\"\n\nfunc main() {\n\tvalue := \"b\"\n\n\tswitch value {\n\tcase \"a\":\n\t\tfmt.Println(\"A\")\n\tcase \"b\":\n\t\tfmt.Println(\"B\")\n\tcase \"c\":\n\t\tfmt.Println(\"C\")\n\tdefault:\n\t\tfmt.Println(\"first default\")\n\t}\n\n\tswitch value {\n\tcase \"a\":\n\t\tfmt.Println(\"A - falling through\")\n\t\tfallthrough\n\tcase \"b\":\n\t\tfmt.Println(\"B - falling through\")\n\t\tfallthrough\n\tcase \"c\":\n\t\tfmt.Println(\"C - falling through\")\n\t\tfallthrough\n\tdefault:\n\t\tfmt.Println(\"second default\")\n\t}\n}\n```\n\nOutput\n\n```bash\nB\nB - falling through\nC - falling through\nsecond default\n```\n\n**[⬆ back to top](#contents)**\n\n### arrays\n---\n\nExamples of slicing, copying, appending, and prepending arrays.\n\n#### Node.js\n\n```node\nconst array = [1, 2, 3, 4, 5]\nconsole.log(array)\n\nconst clone = array.slice(0)\nconsole.log(clone)\n\nconst sub = array.slice(2,4)\nconsole.log(sub)\n\nconst concatenated = clone.concat([6, 7])\nconsole.log(concatenated)\n\nconst prepended = [-2,-1,0].concat(concatenated)\nconsole.log(prepended)\n```\n\nOutput\n\n```bash\n[ 1, 2, 3, 4, 5 ]\n[ 1, 2, 3, 4, 5 ]\n[ 3, 4 ]\n[ 1, 2, 3, 4, 5, 6, 7 ]\n[ -2, -1, 0, 1, 2, 3, 4, 5, 6, 7 ]\n```\n\n#### Go\n\n```go\npackage main\n\nimport \"fmt\"\n\nfunc main() {\n\tarray := []int{1, 2, 3, 4, 5}\n\tfmt.Println(array)\n\n\tclone := make([]int, len(array))\n\tcopy(clone, array)\n\tfmt.Println(clone)\n\n\tsub := array[2:4]\n\tfmt.Println(sub)\n\n\tconcatenated := append(array, []int{6, 7}...)\n\tfmt.Println(concatenated)\n\n\tprepended := append([]int{-2, -1, 0}, concatenated...)\n\tfmt.Println(prepended)\n}\n```\n\nOutput\n\n```bash\n[1 2 3 4 5]\n[1 2 3 4 5]\n[3 4]\n[1 2 3 4 5 6 7]\n[-2 -1 0 1 2 3 4 5 6 7]\n```\n\n**[⬆ back to top](#contents)**\n\n### uint8 arrays\n---\n\n#### Node.js\n\n```javascript\nconst array = new Uint8Array(10)\nconsole.log(array)\n\nconst offset = 1\n\narray.set([1, 2, 3], offset)\nconsole.log(array)\n\nconst sub = array.subarray(2)\nconsole.log(sub)\n\nconst sub2 = array.subarray(2,4)\nconsole.log(sub2)\n\nconsole.log(array)\nconst value = 9\nconst start = 5\nconst end = 10\narray.fill(value, start, end)\nconsole.log(array)\n\nconsole.log(array.byteLength)\n```\n\nOutput\n\n```bash\nUint8Array [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]\nUint8Array [ 0, 1, 2, 3, 0, 0, 0, 0, 0, 0 ]\nUint8Array [ 2, 3, 0, 0, 0, 0, 0, 0 ]\nUint8Array [ 2, 3 ]\nUint8Array [ 0, 1, 2, 3, 0, 0, 0, 0, 0, 0 ]\nUint8Array [ 0, 1, 2, 3, 0, 9, 9, 9, 9, 9 ]\n10\n```\n\n#### Go\n\n```go\npackage main\n\nimport \"fmt\"\n\nfunc main() {\n\tarray := make([]uint8, 10)\n\tfmt.Println(array)\n\n\toffset := 1\n\n\tcopy(array[offset:], []uint8{1, 2, 3})\n\tfmt.Println(array)\n\n\tsub := array[2:]\n\tfmt.Println(sub)\n\n\tsub2 := array[2:4]\n\tfmt.Println(sub2)\n\n\tfmt.Println(array)\n\tvalue := uint8(9)\n\tstart := 5\n\tend := 10\n\tfor i := start; i \u003c end; i++ {\n\t\tarray[i] = value\n\t}\n\tfmt.Println(array)\n\n\tfmt.Println(len(array))\n}\n```\n\nOutput\n\n```bash\n[0 0 0 0 0 0 0 0 0 0]\n[0 1 2 3 0 0 0 0 0 0]\n[2 3 0 0 0 0 0 0]\n[2 3]\n[0 1 2 3 0 0 0 0 0 0]\n[0 1 2 3 0 9 9 9 9 9]\n10\n```\n\n**[⬆ back to top](#contents)**\n\n### array iteration\n---\n\nExamples of iterating, mapping, filtering, and reducing arrays.\n\n#### Node.js\n\n```node\nconst array = ['a', 'b', 'c']\n\narray.forEach((value, i) =\u003e {\n  console.log(i, value)\n})\n\nconst mapped = array.map(value =\u003e {\n  return value.toUpperCase()\n})\n\nconsole.log(mapped)\n\nconst filtered = array.filter((value, i) =\u003e {\n  return i % 2 == 0\n})\n\nconsole.log(filtered)\n\nconst reduced = array.reduce((acc, value, i) =\u003e {\n  if (i % 2 == 0) {\n    acc.push(value.toUpperCase())\n  }\n\n  return acc\n}, [])\n\nconsole.log(reduced)\n```\n\nOutput\n\n```bash\n0 'a'\n1 'b'\n2 'c'\n[ 'A', 'B', 'C' ]\n[ 'a', 'c' ]\n[ 'A', 'C' ]\n```\n\n#### Go\n\n```go\npackage main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\nfunc main() {\n\tarray := []string{\"a\", \"b\", \"c\"}\n\n\tfor i, value := range array {\n\t\tfmt.Println(i, value)\n\t}\n\n\tmapped := make([]string, len(array))\n\tfor i, value := range array {\n\t\tmapped[i] = strings.ToUpper(value)\n\t}\n\n\tfmt.Println(mapped)\n\n\tvar filtered []string\n\tfor i, value := range array {\n\t\tif i%2 == 0 {\n\t\t\tfiltered = append(filtered, value)\n\t\t}\n\t}\n\n\tfmt.Println(filtered)\n\n\tvar reduced []string\n\tfor i, value := range array {\n\t\tif i%2 == 0 {\n\t\t\treduced = append(reduced, strings.ToUpper(value))\n\t\t}\n\t}\n\n\tfmt.Println(reduced)\n}\n```\n\nOutput\n\n```bash\n0 a\n1 b\n2 c\n[A B C]\n[a c]\n[A C]\n```\n\n**[⬆ back to top](#contents)**\n\n### array sorting\n---\n\nExamples of how to sort an array\n\n#### Node.js\n\n```node\nconst stringArray = ['a', 'd', 'z', 'b', 'c', 'y']\nconst stringArraySortedAsc = stringArray.sort((a, b) =\u003e a \u003e b ? 1 : -1)\nconsole.log(stringArraySortedAsc)\n\nconst stringArraySortedDesc = stringArray.sort((a, b) =\u003e a \u003e b ? -1 : 1)\nconsole.log(stringArraySortedDesc)\n\n\nconst numberArray = [1, 3, 5, 9, 4, 2, 0]\nconst numberArraySortedAsc = numberArray.sort((a, b) =\u003e a - b)\nconsole.log(numberArraySortedAsc)\n\nconst numberArraySortedDesc = numberArray.sort((a, b) =\u003e b - a)\nconsole.log(numberArraySortedDesc)\n\nconst collection = [\n    {\n        name: \"Li L\",\n        age: 8\n    },\n    {\n        name: \"Json C\",\n        age: 3\n    },\n    {\n        name: \"Zack W\",\n        age: 15\n    },\n    {\n        name: \"Yi M\",\n        age: 2\n    }\n]\n\nconst collectionSortedByAgeAsc = collection.sort((a, b) =\u003e a.age - b.age)\nconsole.log(collectionSortedByAgeAsc)\n\nconst collectionSortedByAgeDesc = collection.sort((a, b) =\u003e b.age - a.age)\nconsole.log(collectionSortedByAgeDesc)\n```\n\nOutput\n\n```bash\n[ 'a', 'b', 'c', 'd', 'y', 'z' ]\n[ 'z', 'y', 'd', 'c', 'b', 'a' ]\n[ 0, 1, 2, 3, 4, 5, 9 ]\n[ 9, 5, 4, 3, 2, 1, 0 ]\n[ { name: 'Yi M', age: 2 },\n  { name: 'Json C', age: 3 },\n  { name: 'Li L', age: 8 },\n  { name: 'Zack W', age: 15 } ]\n[ { name: 'Zack W', age: 15 },\n  { name: 'Li L', age: 8 },\n  { name: 'Json C', age: 3 },\n  { name: 'Yi M', age: 2 } ]\n```\n\n#### Go\n\n```go\npackage main\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n)\n\ntype Person struct {\n\tName string\n\tAge  int\n}\n\ntype PersonCollection []Person\n\nfunc (pc PersonCollection) Len() int {\n\treturn len(pc)\n}\n\nfunc (pc PersonCollection) Swap(i, j int) {\n\tpc[i], pc[j] = pc[j], pc[i]\n}\n\nfunc (pc PersonCollection) Less(i, j int) bool {\n\t// asc\n\treturn pc[i].Age \u003c pc[j].Age\n}\n\nfunc main() {\n\tintList := []int{1, 3, 5, 9, 4, 2, 0}\n\n\t// asc\n\tsort.Ints(intList)\n\tfmt.Println(intList)\n\t// desc\n\tsort.Sort(sort.Reverse(sort.IntSlice(intList)))\n\tfmt.Println(intList)\n\n\tstringList := []string{\"a\", \"d\", \"z\", \"b\", \"c\", \"y\"}\n\n\t// asc\n\tsort.Strings(stringList)\n\tfmt.Println(stringList)\n\t// desc\n\tsort.Sort(sort.Reverse(sort.StringSlice(stringList)))\n\tfmt.Println(stringList)\n\n\tcollection := []Person{\n\t\t{\"Li L\", 8},\n\t\t{\"Json C\", 3},\n\t\t{\"Zack W\", 15},\n\t\t{\"Yi M\", 2},\n\t}\n\n\t// asc\n\tsort.Sort(PersonCollection(collection))\n\tfmt.Println(collection)\n\t// desc\n\tsort.Sort(sort.Reverse(PersonCollection(collection)))\n\tfmt.Println(collection)\n}\n```\n\nOutput\n\n```bash\n[0 1 2 3 4 5 9]\n[9 5 4 3 2 1 0]\n[a b c d y z]\n[z y d c b a]\n[{Yi M 2} {Json C 3} {Li L 8} {Zack W 15}]\n[{Zack W 15} {Li L 8} {Json C 3} {Yi M 2}]\n```\n\n**[⬆ back to top](#contents)**\n\n### buffers\n---\n\nExamples of how to allocate a buffer, write in big or little endian format, encode to a hex string, and check if buffers are equal.\n\n#### Node.js\n\n```node\nconst buf = Buffer.alloc(6)\n\nlet value = 0x1234567890ab\nlet offset = 0\nlet byteLength = 6\n\nbuf.writeUIntBE(value, offset, byteLength)\n\nlet hexstr = buf.toString('hex')\nconsole.log(hexstr)\n\nconst buf2 = Buffer.alloc(6)\n\nvalue = 0x1234567890ab\noffset = 0\nbyteLength = 6\n\nbuf2.writeUIntLE(value, offset, byteLength)\n\nhexstr = buf2.toString('hex')\nconsole.log(hexstr)\n\nlet isEqual = Buffer.compare(buf, buf2) === 0\nconsole.log(isEqual)\n\nisEqual = Buffer.compare(buf, buf) === 0\nconsole.log(isEqual)\n```\n\nOutput\n\n```bash\n1234567890ab\nab9078563412\nfalse\ntrue\n```\n\n#### Go\n\n```go\npackage main\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"log\"\n\t\"math/big\"\n\t\"reflect\"\n)\n\nfunc writeUIntBE(buffer []byte, value, offset, byteLength int64) {\n\tslice := make([]byte, byteLength)\n\tval := new(big.Int)\n\tval.SetUint64(uint64(value))\n\tvalBytes := val.Bytes()\n\n\tbuf := bytes.NewBuffer(slice)\n\terr := binary.Write(buf, binary.BigEndian, \u0026valBytes)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tslice = buf.Bytes()\n\tslice = slice[int64(len(slice))-byteLength : len(slice)]\n\n\tcopy(buffer[offset:], slice)\n}\n\nfunc writeUIntLE(buffer []byte, value, offset, byteLength int64) {\n\tslice := make([]byte, byteLength)\n\tval := new(big.Int)\n\tval.SetUint64(uint64(value))\n\tvalBytes := val.Bytes()\n\n\ttmp := make([]byte, len(valBytes))\n\tfor i := range valBytes {\n\t\ttmp[i] = valBytes[len(valBytes)-1-i]\n\t}\n\n\tcopy(slice, tmp)\n\tcopy(buffer[offset:], slice)\n}\n\nfunc main() {\n\tbuf := make([]byte, 6)\n\twriteUIntBE(buf, 0x1234567890ab, 0, 6)\n\n\tfmt.Println(hex.EncodeToString(buf))\n\n\tbuf2 := make([]byte, 6)\n\twriteUIntLE(buf2, 0x1234567890ab, 0, 6)\n\n\tfmt.Println(hex.EncodeToString(buf2))\n\n\tisEqual := reflect.DeepEqual(buf, buf2)\n\tfmt.Println(isEqual)\n\n\tisEqual = reflect.DeepEqual(buf, buf)\n\tfmt.Println(isEqual)\n}\n```\n\nOutput\n\n```bash\n1234567890ab\nab9078563412\nfalse\ntrue\n```\n\n**[⬆ back to top](#contents)**\n\n### maps\n---\n\n#### Node.js\n\n```node\nconst map = new Map()\nmap.set('foo', 'bar')\n\nlet found = map.has('foo')\nconsole.log(found)\n\nlet item = map.get('foo')\nconsole.log(item)\n\nmap.delete('foo')\n\nfound = map.has('foo')\nconsole.log(found)\n\nitem = map.get('foo')\nconsole.log(item)\n\nconst map2 = {}\nmap2['foo'] = 'bar'\nitem = map2['foo']\ndelete map2['foo']\n\nconst map3 = new Map()\nmap3.set('foo', 100)\nmap3.set('bar', 200)\nmap3.set('baz', 300)\n\nfor (let [key, value] of map3) {\n  console.log(key, value)\n}\n```\n\nOutput\n\n```bash\ntrue\nbar\nfalse\nundefined\nfoo 100\nbar 200\nbaz 300\n```\n\n#### Go\n\n```go\npackage main\n\nimport \"fmt\"\n\nfunc main() {\n\tmap1 := make(map[string]string)\n\n\tmap1[\"foo\"] = \"bar\"\n\n\titem, found := map1[\"foo\"]\n\tfmt.Println(found)\n\tfmt.Println(item)\n\n\tdelete(map1, \"foo\")\n\n\titem, found = map1[\"foo\"]\n\tfmt.Println(found)\n\tfmt.Println(item)\n\n\tmap2 := make(map[string]int)\n\tmap2[\"foo\"] = 100\n\tmap2[\"bar\"] = 200\n\tmap2[\"baz\"] = 300\n\n\tfor key, value := range map2 {\n\t\tfmt.Println(key, value)\n\t}\n}\n```\n\nOutput\n\n```bash\ntrue\nbar\nfalse\n\nfoo 100\nbar 200\nbaz 300\n```\n\n**[⬆ back to top](#contents)**\n\n### objects\n---\n\n#### Node.js\n\n```node\nconst obj = {\n  someProperties: {\n    'foo': 'bar'\n  },\n  someMethod: (prop) =\u003e {\n    return obj.someProperties[prop]\n  }\n}\n\nlet item =  obj.someProperties['foo']\nconsole.log(item)\n\nitem = obj.someMethod('foo')\nconsole.log(item)\n```\n\nOutput\n\n```bash\nbar\nbar\n```\n\n#### Go\n\n```go\npackage main\n\nimport \"fmt\"\n\ntype Obj struct {\n\tSomeProperties map[string]string\n}\n\nfunc NewObj() *Obj {\n\treturn \u0026Obj{\n\t\tSomeProperties: map[string]string{\n\t\t\t\"foo\": \"bar\",\n\t\t},\n\t}\n}\n\nfunc (o *Obj) SomeMethod(prop string) string {\n\treturn o.SomeProperties[prop]\n}\n\nfunc main() {\n\tobj := NewObj()\n\n\titem := obj.SomeProperties[\"foo\"]\n\tfmt.Println(item)\n\n\titem = obj.SomeMethod(\"foo\")\n\tfmt.Println(item)\n}\n```\n\nOutput\n\n```bash\nbar\nbar\n```\n\n**[⬆ back to top](#contents)**\n\n### functions\n---\n\n#### Node.js\n\n```node\nfunction add(a, b) {\n  return a + b\n}\n\nconst result = add(2,3)\nconsole.log(result)\n```\n\nOutput\n\n```bash\n5\n```\n\n#### Go\n\n```go\npackage main\n\nimport \"fmt\"\n\nfunc add(a int, b int) int {\n\treturn a + b\n}\n\nfunc main() {\n\tresult := add(2, 3)\n\tfmt.Println(result)\n}\n```\n\nOutput\n\n```bash\n5\n```\n\n**[⬆ back to top](#contents)**\n\n### default values\n---\n\n#### Node.js\n\n```node\nfunction greet(name = 'stranger') {\n  return `hello ${name}`\n}\n\nlet message = greet()\nconsole.log(message)\n\nmessage = greet('bob')\nconsole.log(message)\n```\n\nOutput\n\n```bash\nhello stranger\nhello bob\n```\n\n#### Go\n\nuse pointers and check for nil to know if explicitly left blank\n\n```go\npackage main\n\nimport \"fmt\"\n\nfunc greet(name *string) string {\n\tn := \"stranger\"\n\tif name != nil {\n\t\tn = *name\n\t}\n\n\treturn fmt.Sprintf(\"hello %s\", n)\n}\n\nfunc main() {\n\tmessage := greet(nil)\n\tfmt.Println(message)\n\n\tname := \"bob\"\n\tmessage = greet(\u0026name)\n\tfmt.Println(message)\n}\n```\n\nOutput\n\n```bash\nhello stranger\nhello bob\n```\n\n**[⬆ back to top](#contents)**\n\n### destructuring\n---\n\n#### Node.js\n\n```node\nconst obj = { key: 'foo', value: 'bar' }\n\nconst { key, value } = obj\nconsole.log(key, value)\n```\n\nOutput\n\n```bash\nfoo bar\n```\n\n#### Go\n\n```go\npackage main\n\nimport \"fmt\"\n\ntype Obj struct {\n\tKey   string\n\tValue string\n}\n\nfunc (o *Obj) Read() (string, string) {\n\treturn o.Key, o.Value\n}\n\nfunc main() {\n\tobj := Obj{\n\t\tKey:   \"foo\",\n\t\tValue: \"bar\",\n\t}\n\n\t// option 1: multiple variable assignment\n\tkey, value := obj.Key, obj.Value\n\tfmt.Println(key, value)\n\n\t// option 2: return multiple values from a function\n\tkey, value = obj.Read()\n\tfmt.Println(key, value)\n}\n```\n\nOutput\n\n```bash\nfoo bar\nfoo bar\n```\n\n**[⬆ back to top](#contents)**\n\n### spread operator\n---\n\n#### Node.js\n\n```node\nconst array = [1, 2, 3, 4, 5]\n\nconsole.log(...array)\n```\n\nOutput\n\n```bash\n1 2 3 4 5\n```\n\n#### Go\n\n```go\npackage main\n\nimport \"fmt\"\n\nfunc main() {\n\tarray := []byte{1, 2, 3, 4, 5}\n\n\tvar i []interface{}\n\tfor _, value := range array {\n\t\ti = append(i, value)\n\t}\n\n\tfmt.Println(i...)\n}\n```\n\nOutput\n\n```bash\n1 2 3 4 5\n```\n\n**[⬆ back to top](#contents)**\n\n### rest operator\n---\n\n#### Node.js\n\n```node\nfunction sum(...nums) {\n\tlet t = 0\n\n\tfor (let n of nums) {\n\t\tt += n\n\t}\n\n\treturn t\n}\n\nconst total = sum(1, 2, 3, 4, 5)\nconsole.log(total)\n```\n\nOutput\n\n```bash\n15\n```\n\n#### Go\n\n```go\npackage main\n\nimport \"fmt\"\n\nfunc sum(nums ...int) int {\n\tvar t int\n\tfor _, n := range nums {\n\t\tt += n\n\t}\n\n\treturn t\n}\n\nfunc main() {\n\ttotal := sum(1, 2, 3, 4, 5)\n\tfmt.Println(total)\n}\n```\n\nOutput\n\n```bash\n15\n```\n\n**[⬆ back to top](#contents)**\n\n### swapping\n---\n\n#### Node.js\n\n```node\nlet a = 'foo'\nlet b = 'bar'\n\nconsole.log(a, b);\n\n[b, a] = [a, b]\n\nconsole.log(a, b)\n```\n\nOutput\n\n```bash\nfoo bar\nbar foo\n```\n\n#### Go\n\n```go\npackage main\n\nimport \"fmt\"\n\nfunc main() {\n\ta := \"foo\"\n\tb := \"bar\"\n\n\tfmt.Println(a, b)\n\n\tb, a = a, b\n\n\tfmt.Println(a, b)\n}\n```\n\nOutput\n\n```bash\nfoo bar\nbar foo\n```\n\n**[⬆ back to top](#contents)**\n\n### classes\n---\n\nExamples of classes, constructors, instantiation, and \"this\" keyword.\n\n#### Node.js\n\n```node\nclass Foo {\n  constructor(value) {\n    this.item = value\n  }\n\n  getItem() {\n    return this.item\n  }\n\n  setItem(value) {\n    this.item = value\n  }\n}\n\nconst foo = new Foo('bar')\nconsole.log(foo.item)\n\nfoo.setItem('qux')\n\nconst item = foo.getItem()\nconsole.log(item)\n```\n\nOutput\n\n```bash\nbar\nqux\n```\n\n#### Go\n\n(closest thing to a class is to use a structure)\n\n```go\npackage main\n\nimport \"fmt\"\n\ntype Foo struct {\n\tItem string\n}\n\nfunc NewFoo(value string) *Foo {\n\treturn \u0026Foo{\n\t\tItem: value,\n\t}\n}\n\nfunc (f *Foo) GetItem() string {\n\treturn f.Item\n}\n\nfunc (f *Foo) SetItem(value string) {\n\tf.Item = value\n}\n\nfunc main() {\n\tfoo := NewFoo(\"bar\")\n\tfmt.Println(foo.Item)\n\n\tfoo.SetItem(\"qux\")\n\n\titem := foo.GetItem()\n\tfmt.Println(item)\n}\n```\n\nOutput\n\n```bash\nbar\nqux\n```\n\n**[⬆ back to top](#contents)**\n\n### generators\n---\n\n#### Node.js\n\n```node\nfunction *generator() {\n  yield 'hello'\n  yield 'world'\n}\n\nlet gen = generator()\n\nwhile (true) {\n  let { value, done } = gen.next()\n  console.log(value, done)\n\n  if (done) {\n    break\n  }\n}\n\n// alternatively\nfor (let value of generator()) {\n  console.log(value)\n}\n```\n\nOutput\n\n```bash\nhello false\nworld false\nundefined true\nhello\nworld\n```\n\n#### Go\n\n```go\npackage main\n\nimport \"fmt\"\n\nfunc Generator() chan string {\n\tc := make(chan string)\n\n\tgo func() {\n\t\tc \u003c- \"hello\"\n\t\tc \u003c- \"world\"\n\n\t\tclose(c)\n\t}()\n\n\treturn c\n}\n\nfunc GeneratorFunc() func() (string, bool) {\n\ts := []string{\"hello\", \"world\"}\n\ti := -1\n\n\treturn func() (string, bool) {\n\t\ti++\n\t\tif i \u003e= len(s) {\n\t\t\treturn \"\", false\n\t\t}\n\n\t\treturn s[i], true\n\t}\n}\n\nfunc main() {\n\tgen := Generator()\n\tfor {\n\t\tvalue, more := \u003c-gen\n\t\tfmt.Println(value, more)\n\n\t\tif !more {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// alternatively\n\tfor value := range Generator() {\n\t\tfmt.Println(value)\n\t}\n\n\t// alternatively\n\tgenfn := GeneratorFunc()\n\tfor {\n\t\tvalue, more := genfn()\n\t\tfmt.Println(value, more)\n\n\t\tif !more {\n\t\t\tbreak\n\t\t}\n\t}\n}\n```\n\nOutput\n\n```bash\nhello true\nworld true\n false\nhello\nworld\nhello true\nworld true\n false\n```\n\n**[⬆ back to top](#contents)**\n\n### datetime\n---\n\nExamples of parsing, formatting, and getting unix timestamp of dates.\n\n#### Node.js\n\n```node\nconst nowUnix = Date.now()\nconsole.log(nowUnix)\n\nconst datestr = '2019-01-17T09:24:23+00:00'\nconst date = new Date(datestr)\nconsole.log(date.getTime())\nconsole.log(date.toString())\n\nconst futureDate = new Date(date)\nfutureDate.setDate(date.getDate()+14)\nconsole.log(futureDate.toString())\n\nconst formatted = `${String(date.getMonth()+1).padStart(2, 0)}/${String(date.getDate()).padStart(2, 0)}/${date.getFullYear()}`\nconsole.log(formatted)\n```\n\nOutput\n\n```bash\n1547718844168\n1547717063000\nThu Jan 17 2019 01:24:23 GMT-0800 (Pacific Standard Time)\nThu Jan 31 2019 01:24:23 GMT-0800 (Pacific Standard Time)\n01/17/2019\n```\n\n#### Go\n\n```go\npackage main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\nfunc main() {\n\tnowUnix := time.Now().Unix()\n\tfmt.Println(nowUnix)\n\n\tdatestr := \"2019-01-17T09:24:23+00:00\"\n\tdate, err := time.Parse(\"2006-01-02T15:04:05Z07:00\", datestr)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Println(date.Unix())\n\tfmt.Println(date.String())\n\n\tfutureDate := date.AddDate(0, 0, 14)\n\tfmt.Println(futureDate.String())\n\n\tformatted := date.Format(\"01/02/2006\")\n\tfmt.Println(formatted)\n}\n```\n\nOutput\n\n```bash\n1547718844\n1547717063\n2019-01-17 09:24:23 +0000 +0000\n2019-01-31 09:24:23 +0000 +0000\n01/17/2019\n```\n\n**[⬆ back to top](#contents)**\n\n### timeout\n---\n\n#### Node.js\n\n```node\nsetTimeout(callback, 1e3)\n\nfunction callback() {\n  console.log('called')\n}\n```\n\nOutput\n\n```bash\ncalled\n```\n\n#### Go\n\n```go\npackage main\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\t\"time\"\n)\n\nvar wg sync.WaitGroup\n\nfunc callback() {\n\tdefer wg.Done()\n\tfmt.Println(\"called\")\n}\n\nfunc main() {\n\twg.Add(1)\n\ttime.AfterFunc(1*time.Second, callback)\n\twg.Wait()\n}\n```\n\nOutput\n\n```bash\ncalled\n```\n\n**[⬆ back to top](#contents)**\n\n### interval\n---\n\n#### Node.js\n\n```node\nlet i = 0\n\nconst id = setInterval(callback, 1e3)\n\nfunction callback() {\n  console.log('called', i)\n\n  if (i === 3) {\n    clearInterval(id)\n  }\n\n  i++\n}\n```\n\nOutput\n\n```bash\ncalled 0\ncalled 1\ncalled 2\ncalled 3\n```\n\n#### Go\n\n```go\npackage main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\nfunc callback(i int) {\n\tfmt.Println(\"called\", i)\n}\n\nfunc main() {\n\tticker := time.NewTicker(1 * time.Second)\n\n\ti := 0\n\tfor range ticker.C {\n\t\tcallback(i)\n\n\t\tif i == 3 {\n\t\t\tticker.Stop()\n\t\t\tbreak\n\t\t}\n\n\t\ti++\n\t}\n}\n```\n\nOutput\n\n```bash\ncalled 0\ncalled 1\ncalled 2\ncalled 3\n```\n\n**[⬆ back to top](#contents)**\n\n### IIFE\n---\n\nImmediately invoked function expression\n\n#### Node.js\n\n```node\n(function(name) {\n  console.log('hello', name)\n})('bob')\n```\n\nOutput\n\n```bash\nhello bob\n```\n\n#### Go\n\n```go\npackage main\n\nimport \"fmt\"\n\nfunc main() {\n\tfunc(name string) {\n\t\tfmt.Println(\"hello\", name)\n\t}(\"bob\")\n}\n```\n\nOutput\n\n```bash\nhello bob\n```\n\n**[⬆ back to top](#contents)**\n\n### files\n---\n\nExamples of creating, opening, writing, reading, closing, and deleting files.\n\n#### Node.js\n\n```node\nconst fs = require('fs')\n\n// create file\nfs.closeSync(fs.openSync('test.txt', 'w'))\n\n// open file (returns file descriptor)\nconst fd = fs.openSync('test.txt', 'r+')\n\nlet wbuf = Buffer.from('hello world.')\nlet rbuf = Buffer.alloc(12)\nlet off = 0\nlet len = 12\nlet pos = 0\n\n// write file\nfs.writeSync(fd, wbuf, pos)\n\n// read file\nfs.readSync(fd, rbuf, off, len, pos)\n\nconsole.log(rbuf.toString())\n\n// close file\nfs.closeSync(fd)\n\n// delete file\nfs.unlinkSync('test.txt')\n```\n\nOutput\n\n```bash\nhello world.\n```\n\n#### Go\n\n```go\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"syscall\"\n)\n\nfunc main() {\n\t// create file\n\tfile, err := os.Create(\"test.txt\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// close file\n\tfile.Close()\n\n\t// open file\n\tfile, err = os.OpenFile(\"test.txt\", os.O_RDWR, 0755)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// file descriptor\n\tfd := file.Fd()\n\n\t// open file (using file descriptor)\n\tfile = os.NewFile(fd, \"test file\")\n\n\twbuf := []byte(\"hello world.\")\n\trbuf := make([]byte, 12)\n\tvar off int64\n\n\t// write file\n\tif _, err := file.WriteAt(wbuf, off); err != nil {\n\t\tpanic(err)\n\t}\n\n\t// read file\n\tif _, err := file.ReadAt(rbuf, off); err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Println(string(rbuf))\n\n\t// close file (using file descriptor)\n\tif err := syscall.Close(int(fd)); err != nil {\n\t\tpanic(err)\n\t}\n\n\t// delete file\n\tif err := os.Remove(\"test.txt\"); err != nil {\n\t\tpanic(err)\n\t}\n}\n```\n\nOutput\n\n```bash\nhello world.\n```\n\n**[⬆ back to top](#contents)**\n\n### json\n---\n\nExamples of how to parse (unmarshal) and stringify (marshal) JSON.\n\n#### Node.js\n\n```node\nlet jsonstr = '{\"foo\":\"bar\"}'\n\nlet parsed = JSON.parse(jsonstr)\nconsole.log(parsed)\n\njsonstr = JSON.stringify(parsed)\nconsole.log(jsonstr)\n```\n\nOutput\n\n```bash\n{ foo: 'bar' }\n{\"foo\":\"bar\"}\n```\n\n#### Go\n\n```go\npackage main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n)\n\ntype T struct {\n\tFoo string `json:\"foo\"`\n}\n\nfunc main() {\n\tjsonstr := `{\"foo\":\"bar\"}`\n\n\tt := new(T)\n\terr := json.Unmarshal([]byte(jsonstr), t)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Println(t)\n\n\tmarshalled, err := json.Marshal(t)\n\tjsonstr = string(marshalled)\n\tfmt.Println(jsonstr)\n}\n```\n\nOutput\n\n```bash\n\u0026{bar}\n{\"foo\":\"bar\"}\n```\n\n**[⬆ back to top](#contents)**\n\n### big numbers\n---\n\nExamples of creating big number types from and to uint, string, hex, and buffers.\n\n#### Node.js\n\n```node\nlet bn = 75n;\nconsole.log(bn.toString(10))\n\nbn = BigInt('75')\nconsole.log(bn.toString(10))\n\nbn = BigInt(0x4b)\nconsole.log(bn.toString(10))\n\nbn = BigInt('0x4b')\nconsole.log(bn.toString(10))\n\nbn = BigInt('0x' + Buffer.from('4b', 'hex').toString('hex'))\nconsole.log(bn.toString(10))\nconsole.log(Number(bn))\nconsole.log(bn.toString(16))\nconsole.log(Buffer.from(bn.toString(16), 'hex'))\n\nlet bn2 = BigInt(100)\nlet isEqual = bn === bn2\nconsole.log(isEqual)\n\nlet isGreater = bn \u003e bn2\nconsole.log(isGreater)\n\nlet isLesser = bn \u003c bn2\nconsole.log(isLesser)\n```\n\nOutput\n\n```bash\n75\n75\n75\n75\n75\n75\n4b\n\u003cBuffer 4b\u003e\nfalse\nfalse\ntrue\n```\n\n#### Go\n\n```go\npackage main\n\nimport (\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\tbn := new(big.Int)\n\tbn.SetUint64(75)\n\tfmt.Println(bn.String())\n\n\tbn = new(big.Int)\n\tbn.SetString(\"75\", 10)\n\tfmt.Println(bn.String())\n\n\tbn = new(big.Int)\n\tbn.SetUint64(0x4b)\n\tfmt.Println(bn.String())\n\n\tbn = new(big.Int)\n\tbn.SetString(\"4b\", 16)\n\tfmt.Println(bn.String())\n\n\tbn = new(big.Int)\n\tbn.SetBytes([]byte{0x4b})\n\tfmt.Println(bn.String())\n\tfmt.Println(bn.Uint64())\n\tfmt.Println(hex.EncodeToString(bn.Bytes()))\n\tfmt.Println(bn.Bytes())\n\n\tbn2 := big.NewInt(100)\n\tisEqual := bn.Cmp(bn2) == 0\n\tfmt.Println(isEqual)\n\n\tisGreater := bn.Cmp(bn2) == 1\n\tfmt.Println(isGreater)\n\n\tisLesser := bn.Cmp(bn2) == -1\n\tfmt.Println(isLesser)\n}\n```\n\nOutput\n\n```bash\n75\n75\n75\n75\n75\n75\n4b\n[75]\nfalse\nfalse\ntrue\n```\n\n**[⬆ back to top](#contents)**\n\n### promises\n---\n\n#### Node.js\n\n```node\nfunction asyncMethod(value) {\n  return new Promise((resolve, reject) =\u003e {\n    setTimeout(() =\u003e {\n      resolve('resolved: ' + value)\n    }, 1e3)\n  })\n}\n\nfunction main() {\n  asyncMethod('foo')\n    .then(result =\u003e console.log(result))\n    .catch(err =\u003e console.error(err))\n\n  Promise.all([\n    asyncMethod('A'),\n    asyncMethod('B'),\n    asyncMethod('C')\n  ])\n  .then(result =\u003e console.log(result))\n  .catch(err =\u003e console.error(err))\n}\n\nmain()\n```\n\nOutput\n\n```bash\nresolved: foo\n[ 'resolved: A', 'resolved: B', 'resolved: C' ]\n```\n\n#### Go\n\n(closest thing is to use channels)\n\n```go\npackage main\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/prometheus/common/log\"\n)\n\nfunc asyncMethod(value string) chan interface{} {\n\tch := make(chan interface{}, 1)\n\tgo func() {\n\t\ttime.Sleep(1 * time.Second)\n\t\tch \u003c- \"resolved: \" + value\n\t\tclose(ch)\n\t}()\n\n\treturn ch\n}\n\nfunc resolveAll(ch ...chan interface{}) chan interface{} {\n\tvar wg sync.WaitGroup\n\tres := make([]string, len(ch))\n\tresCh := make(chan interface{}, 1)\n\n\tgo func() {\n\t\tfor i, c := range ch {\n\t\t\twg.Add(1)\n\t\t\tgo func(j int, ifcCh chan interface{}) {\n\t\t\t\tifc := \u003c-ifcCh\n\t\t\t\tswitch v := ifc.(type) {\n\t\t\t\tcase error:\n\t\t\t\t\tresCh \u003c- v\n\t\t\t\tcase string:\n\t\t\t\t\tres[j] = v\n\t\t\t\t}\n\t\t\t\twg.Done()\n\t\t\t}(i, c)\n\t\t}\n\n\t\twg.Wait()\n\t\tresCh \u003c- res\n\t\tclose(resCh)\n\t}()\n\n\treturn resCh\n}\n\nfunc main() {\n\tvar wg sync.WaitGroup\n\twg.Add(2)\n\n\tgo func() {\n\t\tresult := \u003c-asyncMethod(\"foo\")\n\t\tswitch v := result.(type) {\n\t\tcase string:\n\t\t\tfmt.Println(v)\n\t\tcase error:\n\t\t\tlog.Errorln(v)\n\t\t}\n\n\t\twg.Done()\n\t}()\n\n\tgo func() {\n\t\tresult := \u003c-resolveAll(\n\t\t\tasyncMethod(\"A\"),\n\t\t\tasyncMethod(\"B\"),\n\t\t\tasyncMethod(\"C\"),\n\t\t)\n\n\t\tswitch v := result.(type) {\n\t\tcase []string:\n\t\t\tfmt.Println(v)\n\t\tcase error:\n\t\t\tlog.Errorln(v)\n\t\t}\n\n\t\twg.Done()\n\t}()\n\n\twg.Wait()\n}\n```\n\nOutput\n\n```bash\nresolved: foo\n[resolved: A resolved: B resolved: C]\n```\n\n**[⬆ back to top](#contents)**\n\n### async/await\n---\n\n#### Node.js\n\n```node\nfunction hello(name) {\n  return new Promise((resolve, reject) =\u003e {\n    setTimeout(() =\u003e {\n      if (name === 'fail') {\n        reject(new Error('failed'))\n      } else {\n        resolve('hello ' + name)\n      }\n    }, 1e3)\n  })\n}\n\nasync function main() {\n  try {\n    let output = await hello('bob')\n    console.log(output)\n\n    output = await hello('fail')\n    console.log(output)\n  } catch(err) {\n    console.log(err.message)\n  }\n}\n\nmain()\n```\n\nOutput\n\n```bash\nhello bob\nfailed\n```\n\n#### Go\n\n(closest thing is to use channels)\n\n```go\npackage main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/prometheus/common/log\"\n)\n\nfunc hello(name string) chan interface{} {\n\tch := make(chan interface{}, 1)\n\tgo func() {\n\t\ttime.Sleep(1 * time.Second)\n\t\tif name == \"fail\" {\n\t\t\tch \u003c- errors.New(\"failed\")\n\t\t} else {\n\t\t\tch \u003c- \"hello \" + name\n\t\t}\n\t}()\n\n\treturn ch\n}\n\nfunc main() {\n\tresult := \u003c-hello(\"bob\")\n\tswitch v := result.(type) {\n\tcase string:\n\t\tfmt.Println(v)\n\tcase error:\n\t\tlog.Errorln(v)\n\t}\n\n\tresult = \u003c-hello(\"fail\")\n\tswitch v := result.(type) {\n\tcase string:\n\t\tfmt.Println(v)\n\tcase error:\n\t\tlog.Errorln(v)\n\t}\n}\n```\n\nOutput\n\n```bash\nhello bob\nfailed\n```\n\n**[⬆ back to top](#contents)**\n\n### streams\n---\n\nExamples of reading and writing streams\n\n#### Node.js\n\n```node\nconst { Readable, Writable } = require('stream')\n\nconst inStream = new Readable()\n\ninStream.push(Buffer.from('foo'))\ninStream.push(Buffer.from('bar'))\ninStream.push(null) // end stream\ninStream.pipe(process.stdout)\n\nconst outStream = new Writable({\n  write(chunk, encoding, callback) {\n    console.log('received: ' + chunk.toString('utf8'))\n    callback()\n  }\n})\n\noutStream.write(Buffer.from('abc'))\noutStream.write(Buffer.from('xyz'))\noutStream.end()\n```\n\nOutput\n\n```bash\nfoobar\nreceived: abc\nreceived: xyz\n```\n\n#### Go\n\n```go\npackage main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"runtime\"\n)\n\nfunc main() {\n\tinStream := new(bytes.Buffer)\n\tw := bufio.NewWriter(inStream)\n\t_, err := w.Write([]byte(\"foo\"))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t_, err = w.Write([]byte(\"bar\"))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\terr = w.Flush()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tinStream.WriteTo(os.Stdout)\n\tfmt.Print(\"\\n\")\n\n\toutStream := new(bytes.Buffer)\n\toutStream.Write([]byte(\"abc\\n\"))\n\toutStream.Write([]byte(\"xyc\\n\"))\n\tpiper, pipew := io.Pipe()\n\n\tgo func() {\n\t\tsc := bufio.NewScanner(piper)\n\t\tfor sc.Scan() {\n\t\t\tfmt.Println(\"received: \" + sc.Text())\n\t\t}\n\t\tif err := sc.Err(); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tos.Exit(0)\n\t}()\n\n\tgo func() {\n\t\tdefer pipew.Close()\n\t\tio.Copy(pipew, outStream)\n\t}()\n\n\tdefer runtime.Goexit()\n}\n```\n\nOutput\n\n```bash\nfoobar\nreceived: abc\nreceived: xyc\n```\n\n**[⬆ back to top](#contents)**\n\n### event emitter\n---\n\n#### Node.js\n\n```node\nconst EventEmitter = require('events')\nclass MyEmitter extends EventEmitter {}\nconst myEmitter = new MyEmitter()\n\nmyEmitter.on('my-event', msg =\u003e {\n  console.log(msg)\n})\n\nmyEmitter.on('my-other-event', msg =\u003e {\n  console.log(msg)\n})\n\nmyEmitter.emit('my-event', 'hello world')\nmyEmitter.emit('my-other-event', 'hello other world')\n```\n\nOutput\n\n```bash\nhello world\nhello other world\n```\n\n#### Go\n\n(closest thing is to use channels)\n\n```go\npackage main\n\nimport (\n\t\"fmt\"\n)\n\ntype MyEmitter map[string]chan string\n\nfunc main() {\n\tmyEmitter := MyEmitter{}\n\tmyEmitter[\"my-event\"] = make(chan string)\n\tmyEmitter[\"my-other-event\"] = make(chan string)\n\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase msg := \u003c-myEmitter[\"my-event\"]:\n\t\t\t\tfmt.Println(msg)\n\t\t\tcase msg := \u003c-myEmitter[\"my-other-event\"]:\n\t\t\t\tfmt.Println(msg)\n\t\t\t}\n\t\t}\n\t}()\n\n\tmyEmitter[\"my-event\"] \u003c- \"hello world\"\n\tmyEmitter[\"my-other-event\"] \u003c- \"hello other world\"\n}\n```\n\nOutput\n\n```bash\nhello world\nhello other world\n```\n\n**[⬆ back to top](#contents)**\n\n### errors\n---\n\n#### Node.js\n\n```node\nconst err1 = new Error('some error')\n\nconsole.log(err1)\n\nclass FooError extends Error{\n  constructor(message) {\n    super(message)\n    this.name = 'FooError'\n    this.message = message\n  }\n\n  toString() {\n    return this.message\n  }\n}\n\nconst err2 = new FooError('my custom error')\n\nconsole.log(err2)\n```\n\nOutput\n\n```bash\nError: some error\n{ FooError: my custom error }\n```\n\n#### Go\n\n```go\npackage main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\ntype FooError struct {\n\ts string\n}\n\nfunc (f *FooError) Error() string {\n\treturn f.s\n}\n\nfunc NewFooError(s string) error {\n\treturn \u0026FooError{s}\n}\n\nfunc main() {\n\terr1 := errors.New(\"some error\")\n\tfmt.Println(err1)\n\n\terr2 := NewFooError(\"my custom error\")\n\tfmt.Println(err2)\n}\n```\n\nOutput\n\n```bash\nsome error\nmy custom error\n```\n\n**[⬆ back to top](#contents)**\n\n### try/catch\n---\n\n#### Node.js\n\n```node\nfunction foo(fail) {\n  if (fail) {\n    throw Error('my error')\n  }\n}\n\nfunction main() {\n  try {\n    foo(true)\n  } catch(err) {\n    console.log(`caught error: ${err.message}`)\n  }\n}\n\nmain()\n```\n\nOutput\n\n```bash\ncaught error: my error\n```\n\n#### Go\n\n```go\npackage main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\nfunc foo(fail bool) error {\n\tif fail {\n\t\treturn errors.New(\"my error\")\n\t}\n\n\treturn nil\n}\n\nfunc main() {\n\terr := foo(true)\n\tif err != nil {\n\t\tfmt.Printf(\"caught error: %s\\n\", err.Error())\n\t}\n}\n```\n\nOutput\n\n```bash\ncaught error: my error\n```\n\n**[⬆ back to top](#contents)**\n\n### exceptions\n---\n\n#### Node.js\n\n```node\nfunction foo() {\n  throw Error('my exception')\n}\n\nfunction main() {\n  foo()\n}\n\nprocess.on('uncaughtException', err =\u003e {\n  console.log(`caught exception: ${err.message}`)\n  process.exit(1)\n})\n\nmain()\n```\n\nOutput\n\n```bash\ncaught exception: my exception\n```\n\n#### Go\n\n```go\npackage main\n\nimport (\n\t\"fmt\"\n)\n\nfunc foo() {\n\tpanic(\"my exception\")\n}\n\nfunc main() {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tfmt.Printf(\"caught exception: %s\", r)\n\t\t}\n\t}()\n\n\tfoo()\n}\n```\n\nOutput\n\n```bash\ncaught exception: my exception\n```\n\n**[⬆ back to top](#contents)**\n\n### regex\n---\n\n#### Node.js\n\n```node\nlet input = 'foobar'\nlet replaced = input.replace(/foo(.*)/i, 'qux$1')\nconsole.log(replaced)\n\nlet match = /o{2}/i.test(input)\nconsole.log(match)\n\ninput = '111-222-333'\nlet matches = input.match(/([0-9]+)/gi)\nconsole.log(matches)\n```\n\nOutput\n\n```bash\nquxbar\ntrue\n[ '111', '222', '333' ]\n```\n\n#### Go\n\n```go\npackage main\n\nimport (\n\t\"fmt\"\n\t\"regexp\"\n)\n\nfunc main() {\n\tinput := \"foobar\"\n\tre := regexp.MustCompile(`(?i)foo(.*)`)\n\treplaced := re.ReplaceAllString(input, \"qux$1\")\n\tfmt.Println(replaced)\n\n\tre = regexp.MustCompile(`(?i)o{2}`)\n\tmatch := re.Match([]byte(input))\n\tfmt.Println(match)\n\n\tinput = \"111-222-333\"\n\tre = regexp.MustCompile(`(?i)([0-9]+)`)\n\tmatches := re.FindAllString(input, -1)\n\tfmt.Println(matches)\n}\n```\n\nOutput\n\n```bash\nquxbar\ntrue\n[111 222 333]\n```\n\n**[⬆ back to top](#contents)**\n\n### exec (sync)\n---\n\n#### Node.js\n\n```javascript\nconst { execSync } = require('child_process')\n\nconst output = execSync(`echo 'hello world'`)\n\nconsole.log(output.toString())\n```\n\nOutput\n\n```bash\nhello world\n```\n\n#### Go\n\n```go\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os/exec\"\n)\n\nfunc main() {\n\toutput, err := exec.Command(\"echo\", \"hello world\").Output()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Println(string(output))\n}\n```\n\nOutput\n\n```bash\nhello world\n```\n\n**[⬆ back to top](#contents)**\n\n### exec (async)\n---\n\n#### Node.js\n\n```javascript\nconst { exec } = require('child_process')\n\nexec(`echo 'hello world'`, (error, stdout, stderr) =\u003e {\n  if (error) {\n    console.error(err)\n  }\n\n  if (stderr) {\n    console.error(stderr)\n  }\n\n  if (stdout) {\n    console.log(stdout)\n  }\n})\n```\n\nOutput\n\n```bash\nhello world\n```\n\n#### Go\n\n```go\npackage main\n\nimport (\n\t\"os\"\n\t\"os/exec\"\n)\n\nfunc main() {\n\tcmd := exec.Command(\"echo\", \"hello world\")\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tcmd.Run()\n}\n```\n\nOutput\n\n```bash\nhello world\n```\n\n**[⬆ back to top](#contents)**\n\n### tcp server\n---\n\n#### Node.js\n\n```node\nconst net = require('net')\n\nfunction handler(socket) {\n\tsocket.write('Received: ')\n\tsocket.pipe(socket)\n}\n\nconst server = net.createServer(handler)\nserver.listen(3000)\n```\n\nOutput\n\n```bash\n$ echo 'hello' | nc localhost 3000\nReceived: hello\n```\n\n#### Go\n\n```go\npackage main\n\nimport (\n\t\"bufio\"\n\t\"net\"\n)\n\nfunc handler(conn net.Conn) {\n\tdefer conn.Close()\n\treader := bufio.NewReader(conn)\n\n\tfor {\n\t\tmessage, err := reader.ReadString('\\n')\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tconn.Write([]byte(\"Received: \"))\n\t\tconn.Write([]byte(message))\n\t}\n}\n\nfunc main() {\n\tlistener, err := net.Listen(\"tcp\", \":3000\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer listener.Close()\n\n\tfor {\n\t\tconn, err := listener.Accept()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tgo handler(conn)\n\t}\n}\n```\n\nOutput\n\n```bash\n$ echo 'hello' | nc localhost 3000\nReceived: hello\n```\n\n**[⬆ back to top](#contents)**\n\n### udp server\n---\n\n#### Node.js\n\n```node\nconst dgram = require('dgram')\nconst server = dgram.createSocket('udp4')\n\nserver.on('error', err =\u003e {\n  console.error(err)\n  server.close()\n})\n\nserver.on('message', (msg, rinfo) =\u003e {\n  const data = msg.toString('utf8').trim()\n  console.log(`received: ${data} from ${rinfo.address}:${rinfo.port}`)\n})\n\nserver.on('listening', () =\u003e {\n  const address = server.address()\n  console.log(`server listening ${address.address}:${address.port}`)\n})\n\nserver.bind(3000)\n```\n\nOutput\n\n```bash\n$ echo 'hello world' \u003e /dev/udp/0.0.0.0/3000\n\nserver listening 0.0.0.0:3000\nreceived: hello world from 127.0.0.1:51452\n```\n\n#### Go\n\n```go\npackage main\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"strings\"\n)\n\nfunc main() {\n\tconn, err := net.ListenUDP(\"udp\", \u0026net.UDPAddr{\n\t\tPort: 3000,\n\t\tIP:   net.ParseIP(\"0.0.0.0\"),\n\t})\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer conn.Close()\n\tfmt.Printf(\"server listening %s\\n\", conn.LocalAddr().String())\n\n\tfor {\n\t\tmessage := make([]byte, 20)\n\t\trlen, remote, err := conn.ReadFromUDP(message[:])\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tdata := strings.TrimSpace(string(message[:rlen]))\n\t\tfmt.Printf(\"received: %s from %s\\n\", data, remote)\n\t}\n}\n```\n\nOutput\n\n```bash\n$ echo 'hello world' \u003e /dev/udp/0.0.0.0/3000\n\nserver listening [::]:3000\nreceived: hello world from 127.0.0.1:50275\n```\n\n**[⬆ back to top](#contents)**\n\n### http server\n---\n\n#### Node.js\n\n```node\nconst http = require('http')\n\nfunction handler(request, response) {\n  response.writeHead(200, { 'Content-type':'text/plain' })\n  response.write('hello world')\n  response.end()\n}\n\nconst server = http.createServer(handler)\nserver.listen(8080)\n```\n\nOutput\n\n```bash\n$ curl http://localhost:8080\nhello world\n```\n\n#### Go\n\n```go\npackage main\n\nimport (\n\t\"net/http\"\n)\n\nfunc handler(w http.ResponseWriter, r *http.Request) {\n\tw.WriteHeader(200)\n\tw.Write([]byte(\"hello world\"))\n}\n\nfunc main() {\n\thttp.HandleFunc(\"/\", handler)\n\tif err := http.ListenAndServe(\":8080\", nil); err != nil {\n\t\tpanic(err)\n\t}\n}\n```\n\nOutput\n\n```bash\n$ curl http://localhost:8080\nhello world\n```\n\n**[⬆ back to top](#contents)**\n\n### url parse\n---\n\n#### Node.js\n\n```node\nconst url = require('url')\nconst qs = require('querystring')\n\nconst urlstr = 'http://bob:secret@sub.example.com:8080/somepath?foo=bar'\n\nconst parsed = url.parse(urlstr)\nconsole.log(parsed.protocol)\nconsole.log(parsed.auth)\nconsole.log(parsed.port)\nconsole.log(parsed.hostname)\nconsole.log(parsed.pathname)\nconsole.log(qs.parse(parsed.search.substr(1)))\n```\n\nOutput\n\n```bash\nhttp:\nbob:secret\n8080\nsub.example.com\n/somepath\n{ foo: 'bar' }\n```\n\n#### Go\n\n```go\npackage main\n\nimport (\n\t\"fmt\"\n\t\"net/url\"\n)\n\nfunc main() {\n\turlstr := \"http://bob:secret@sub.example.com:8080/somepath?foo=bar\"\n\n\tu, err := url.Parse(urlstr)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Println(u.Scheme)\n\tfmt.Println(u.User)\n\tfmt.Println(u.Port())\n\tfmt.Println(u.Hostname())\n\tfmt.Println(u.Path)\n\tfmt.Println(u.Query())\n}\n```\n\nOutput\n\n```bash\nhttp\nbob:secret\n8080\nsub.example.com\n/somepath\nmap[foo:[bar]]\n```\n\n**[⬆ back to top](#contents)**\n\n### gzip\n---\n\n#### Node.js\n\n```node\nconst zlib = require('zlib')\n\nconst data = Buffer.from('hello world', 'utf-8')\n\nzlib.gzip(data, (err, compressed) =\u003e {\n  if (err) {\n    console.error(err)\n  }\n\n  console.log(compressed)\n\n  zlib.unzip(compressed, (err, decompressed) =\u003e {\n    if (err) {\n      console.error(err)\n    }\n\n    console.log(decompressed.toString())\n  })\n})\n\n```\n\nOutput\n\n```bash\n\u003cBuffer 1f 8b 08 00 00 00 00 00 00 13 cb 48 cd c9 c9 57 28 cf 2f ca 49 01 00 85 11 4a 0d 0b 00 00 00\u003e\nhello world\n```\n\n#### Go\n\n```go\npackage main\n\nimport (\n\t\"bytes\"\n\t\"compress/gzip\"\n\t\"fmt\"\n)\n\nfunc main() {\n\tdata := []byte(\"hello world\")\n\n\tcompressed := new(bytes.Buffer)\n\tw := gzip.NewWriter(compressed)\n\tif _, err := w.Write(data); err != nil {\n\t\tpanic(err)\n\t}\n\tif err := w.Close(); err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Println(compressed.Bytes())\n\n\tdecompressed := new(bytes.Buffer)\n\tr, err := gzip.NewReader(compressed)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t_, err = decompressed.ReadFrom(r)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Println(string(decompressed.Bytes()))\n}\n```\n\nOutput\n\n```bash\n[31 139 8 0 0 0 0 0 0 255 202 72 205 201 201 87 40 207 47 202 73 1 4 0 0 255 255 133 17 74 13 11 0 0 0]\nhello world\n```\n\n**[⬆ back to top](#contents)**\n\n### dns\n---\n\nDNS lookup examples\n\n#### Node.js\n\n```node\nconst dns = require('dns')\n\ndns.resolveNs('google.com', (err, ns) =\u003e {\n  if (err) {\n    console.error(err)\n  }\n\n  console.log(ns)\n})\n\ndns.resolve4('google.com', (err, ips) =\u003e {\n  if (err) {\n    console.error(err)\n  }\n\n  console.log(ips)\n})\n\ndns.resolveMx('google.com', (err, mx) =\u003e {\n  if (err) {\n    console.error(err)\n  }\n\n  console.log(mx)\n})\n\ndns.resolveTxt('google.com', (err, txt) =\u003e {\n  if (err) {\n    console.error(err)\n  }\n\n  console.log(txt)\n})\n\ndns.setServers(['1.1.1.1'])\nconsole.log(dns.getServers())\n\ndns.resolveNs('google.com', (err, ns) =\u003e {\n  if (err) {\n    console.error(err)\n  }\n\n  console.log(ns)\n})\n```\n\nOutput\n\n```bash\n[\n  'ns2.google.com',\n  'ns3.google.com',\n  'ns4.google.com',\n  'ns1.google.com'\n]\n[ '172.217.11.78' ]\n[ { exchange: 'alt4.aspmx.l.google.com', priority: 50 },\n  { exchange: 'alt2.aspmx.l.google.com', priority: 30 },\n  { exchange: 'alt3.aspmx.l.google.com', priority: 40 },\n  { exchange: 'aspmx.l.google.com', priority: 10 },\n  { exchange: 'alt1.aspmx.l.google.com', priority: 20 } ]\n[ [ 'v=spf1 include:_spf.google.com ~all' ],\n  [ 'docusign=05958488-4752-4ef2-95eb-aa7ba8a3bd0e' ],\n  [ 'facebook-domain-verification=22rm551cu4k0ab0bxsw536tlds4h95' ],\n  [ 'globalsign-smime-dv=CDYX+XFHUw2wml6/Gb8+59BsH31KzUr6c1l2BPvqKX8=' ] ]\n[ '1.1.1.1' ]\n[\n  'ns1.google.com',\n  'ns2.google.com',\n  'ns4.google.com',\n  'ns3.google.com'\n]\n```\n\n#### Go\n\n```go\npackage main\n\nimport (\n\t\"fmt\"\n\t\"net\"\n)\n\nfunc main() {\n\tns, err := net.LookupNS(\"google.com\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Printf(\"%s\\n\", ns)\n\n\tips, err := net.LookupIP(\"google.com\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Println(ips)\n\n\tmx, err := net.LookupMX(\"google.com\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Println(mx)\n\n\ttxt, err := net.LookupTXT(\"google.com\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Println(txt)\n\n\tr := \u0026net.Resolver{\n\t\tPreferGo: true,\n\t\tDial: func(ctx context.Context, network, address string) (net.Conn, error) {\n\t\t\td := net.Dialer{\n\t\t\t\tTimeout: time.Millisecond * time.Duration(10_000),\n\t\t\t}\n\t\t\treturn d.DialContext(ctx, \"udp\", \"1.1.1.1:53\")\n\t\t},\n\t}\n\n\tns, _ = r.LookupNS(context.Background(), \"google.com\")\n\tfmt.Printf(\"%s\", ns)\n}\n```\n\nOutput\n\n```bash\n[%!s(*net.NS=\u0026{ns3.google.com.}) %!s(*net.NS=\u0026{ns4.google.com.}) %!s(*net.NS=\u0026{ns1.google.com.}) %!s(*net.NS=\u0026{ns2.google.com.})]\n[172.217.5.78 2607:f8b0:4007:80d::200e]\n[0xc0000ba2e0 0xc0000ba260 0xc0000ba2a0 0xc0000ba280 0xc0000ba300]\n[facebook-domain-verification=22rm551cu4k0ab0bxsw536tlds4h95 docusign=05958488-4752-4ef2-95eb-aa7ba8a3bd0e v=spf1 include:_spf.google.com ~all globalsign-smime-dv=CDYX+XFHUw2wml6/Gb8+59BsH31KzUr6c1l2BPvqKX8=]\n[%!s(*net.NS=\u0026{ns2.google.com.}) %!s(*net.NS=\u0026{ns1.google.com.}) %!s(*net.NS=\u0026{ns3.google.com.}) %!s(*net.NS=\u0026{ns4.google.com.})]\n```\n\n**[⬆ back to top](#contents)**\n\n### crypto\n---\n\n#### Node.js\n\n```node\nconst crypto = require('crypto')\n\nconst hash = crypto.createHash('sha256').update(Buffer.from('hello')).digest()\n\nconsole.log(hash.toString('hex'))\n```\n\nOutput\n\n```bash\n2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824\n```\n\n#### Go\n\n```go\npackage main\n\nimport (\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"fmt\"\n)\n\nfunc main() {\n\thash := sha256.Sum256([]byte(\"hello\"))\n\n\tfmt.Println(hex.EncodeToString(hash[:]))\n}\n```\n\nOutput\n\n```bash\n2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824\n```\n\n**[⬆ back to top](#contents)**\n\n### env vars\n---\n\n#### Node.js\n\n```node\nconst key = process.env['API_KEY']\n\nconsole.log(key)\n```\n\nOutput\n\n```bash\n$ API_KEY=foobar node examples/env_vars.js\nfoobar\n```\n\n#### Go\n\n```go\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tkey := os.Getenv(\"API_KEY\")\n\n\tfmt.Println(key)\n}\n```\n\nOutput\n\n```bash\n$ API_KEY=foobar go run examples/env_vars.go\nfoobar\n```\n\n**[⬆ back to top](#contents)**\n\n### cli args\n---\n\n#### Node.js\n\n```node\nconst args = process.argv.slice(2)\n\nconsole.log(args)\n```\n\nOutput\n\n```bash\n$ node examples/cli_args.js foo bar qux\n[ 'foo', 'bar', 'qux' ]\n```\n\n#### Go\n\n```go\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\targs := os.Args[1:]\n\tfmt.Println(args)\n}\n```\n\nOutput\n\n```bash\n$ go run examples/cli_args.go foo bar qux\n[foo bar qux]\n```\n\n**[⬆ back to top](#contents)**\n\n### cli flags\n---\n\n#### Node.js\n\n```node\nconst yargs = require('yargs')\n\nconst { foo='default value', qux=false } = yargs.argv\nconsole.log('foo:', foo)\nconsole.log('qux:', qux)\n```\n\nOutput\n\n```bash\n$ node examples/cli_flags.js --foo='bar' --qux=true\nfoo: bar\nqux: true\n```\n\n#### Go\n\n```go\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n)\n\nfunc main() {\n\tvar foo string\n\tflag.StringVar(\u0026foo, \"foo\", \"default value\", \"a string var\")\n\n\tvar qux bool\n\tflag.BoolVar(\u0026qux, \"qux\", false, \"a bool var\")\n\n\tflag.Parse()\n\n\tfmt.Println(\"foo:\", foo)\n\tfmt.Println(\"qux:\", qux)\n}\n```\n\nOutput\n\n```bash\n$ go run examples/cli_flags.go -foo='bar' -qux=true\nfoo: bar\nqux: true\n```\n\n**[⬆ back to top](#contents)**\n\n### stdout\n---\n\n#### Node.js\n\n```node\nprocess.stdout.write('hello world\\n')\n```\n\nOutput\n\n```bash\nhello world\n```\n\n#### Go\n\n```go\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tfmt.Fprint(os.Stdout, \"hello world\\n\")\n}\n```\n\nOutput\n\n```bash\nhello world\n```\n\n**[⬆ back to top](#contents)**\n\n### stderr\n---\n\n#### Node.js\n\n```node\nprocess.stderr.write('hello error\\n')\n```\n\nOutput\n\n```bash\nhello error\n```\n\n#### Go\n\n```go\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tfmt.Fprint(os.Stderr, \"hello error\\n\")\n}\n```\n\nOutput\n\n```bash\nhello error\n```\n\n**[⬆ back to top](#contents)**\n\n### stdin\n---\n\n#### Node.js\n\n```node\nconst stdin = process.openStdin()\n\nprocess.stdout.write('Enter name: ')\n\nstdin.addListener('data', text =\u003e {\n  const name = text.toString().trim()\n  console.log('Your name is: ' + name)\n\n  stdin.pause()\n})\n```\n\nOutput\n\n```bash\nEnter name: bob\nYour name is: bob\n```\n\n#### Go\n\n```go\npackage main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n)\n\nfunc main() {\n\treader := bufio.NewReader(os.Stdin)\n\tfmt.Print(\"Enter name: \")\n\n\ttext, err := reader.ReadString('\\n')\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tname := strings.TrimSpace(text)\n\tfmt.Printf(\"Your name is: %s\\n\", name)\n}\n```\n\nOutput\n\n```bash\nEnter name: bob\nYour name is: bob\n```\n\n**[⬆ back to top](#contents)**\n\n### modules\n---\n\n#### Node.js\n\n```bash\n# initializing metadata and dependencies file (package.json)\n$ npm init\n\n# installing a module\n$ npm install moment --save\n\n# updating a module\n$ npm install moment@latest --save\n\n# removing a module\n$ npm uninstall moment --save\n\n# pruning modules (removing unused modules)\n$ npm prune\n\n# publishing a module\n$ npm publish\n```\n\n```node\n// importing a module\nconst moment = require('moment')\n\nconst now = moment().unix()\nconsole.log(now)\n```\n\nOutput\n\n```bash\n1546595748\n```\n\n```node\n// exporting a module\nmodule.exports = {\n  greet(name) {\n    console.log(`hello ${name}`)\n  }\n}\n```\n\n```node\n// importing exported module\nconst greeter = require('./greeter')\n\ngreeter.greet('bob')\n```\n\nOutput\n\n```bash\nhello bob\n```\n\n#### Go\n\nSetup\n\n```bash\n# enable Go modules support\nGO111MODULE=on\n\n# initializing dependencies file (go.mod)\n$ go mod init\n\n# installing a module\n$ go get github.com/go-shadow/moment\n\n# updating a module\n$ go get -u github.com/go-shadow/moment\n\n# removing a module\n$ rm -rf $GOPATH/pkg/mod/github.com/go-shadow/moment@v\u003ctag\u003e-\u003cchecksum\u003e/\n\n# pruning modules (removing unused modules from dependencies file)\n$ go mod tidy\n\n# download modules being used to local vendor directory (equivalent of downloading node_modules locally)\n$ go mod vendor\n\n# publishing a module:\n# Note: Go doesn't have an index of repositories like NPM.\n# Go modules are hosted as public git repositories.\n# To publish, simply push to the repository and tag releases.\n```\n\n```go\npackage main\n\nimport (\n\t\"fmt\"\n\n\t// importing a module\n\t\"github.com/go-shadow/moment\"\n)\n\nfunc main() {\n\tnow := moment.New().Now().Unix()\n\tfmt.Println(now)\n}\n```\n\nOutput\n\n```bash\n1546595748\n```\n\n```go\npackage greeter\n\nimport (\n\t\"fmt\"\n)\n\n// exporting a module (use a capitalized name to export function)\nfunc Greet(name string) {\n\tfmt.Printf(\"hello %s\", name)\n}\n```\n\n```go\npackage main\n\nimport (\n\t// importing exported module\n\tgreeter \"github.com/miguelmota/golang-for-nodejs-developers/examples/greeter_go\"\n)\n\nfunc main() {\n\tgreeter.Greet(\"bob\")\n}\n```\n\nOutput\n\n```bash\nhello bob\n```\n\n**[⬆ back to top](#contents)**\n\n### stack trace\n---\n\n#### Node.js\n\n```node\nfunction foo() {\n  throw new Error('failed')\n}\n\ntry {\n  foo()\n} catch(err) {\n  console.trace(err)\n}\n\n```\n\nOutput\n\n```bash\nTrace: Error: failed\n    at foo (/Users/bob/examples/stack_trace.js:2:9)\n    at Object.\u003canonymous\u003e (/Users/bob/examples/stack_trace.js:6:3)\n    at Module._compile (internal/modules/cjs/loader.js:688:30)\n    at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)\n    at Module.load (internal/modules/cjs/loader.js:598:32)\n    at tryModuleLoad (internal/modules/cjs/loader.js:537:12)\n    at Function.Module._load (internal/modules/cjs/loader.js:529:3)\n    at Function.Module.runMain (internal/modules/cjs/loader.js:741:12)\n    at startup (internal/bootstrap/node.js:285:19)\n    at bootstrapNodeJSCore (internal/bootstrap/node.js:739:3)\n    at Object.\u003canonymous\u003e (/Users/bob/examples/stack_trace.js:8:11)\n    at Module._compile (internal/modules/cjs/loader.js:688:30)\n    at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)\n    at Module.load (internal/modules/cjs/loader.js:598:32)\n    at tryModuleLoad (internal/modules/cjs/loader.js:537:12)\n    at Function.Module._load (internal/modules/cjs/loader.js:529:3)\n    at Function.Module.runMain (internal/modules/cjs/loader.js:741:12)\n    at startup (internal/bootstrap/node.js:285:19)\n    at bootstrapNodeJSCore (internal/bootstrap/node.js:739:3)\n```\n\n#### Go\n\n```go\npackage main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"runtime/debug\"\n)\n\nfunc foo() {\n\tpanic(errors.New(\"failed\"))\n}\n\nfunc main() {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tfmt.Println(string(debug.Stack()))\n\t\t}\n\t}()\n\n\tfoo()\n}\n```\n\nOutput\n\n```bash\ngoroutine 1 [running]:\nruntime/debug.Stack(0xc000090eb8, 0x10a8400, 0xc00007e1c0)\n        /Users/mota/.gvm/gos/go1.11/src/runtime/debug/stack.go:24 +0xa7\nmain.main.func1()\n        /Users/bob/examples/stack_trace.go:16 +0x46\npanic(0x10a8400, 0xc00007e1c0)\n        /Users/mota/.gvm/gos/go1.11/src/runtime/panic.go:513 +0x1b9\nmain.foo(...)\n        /Users/bob/examples/stack_trace.go:10\nmain.main()\n        /Users/bob/examples/stack_trace.go:20 +0xa2\n```\n\n**[⬆ back to top](#contents)**\n\n### databases\n---\n\nExample of creating a table, inserting rows, and reading rows from a sqlite3 database\n\n#### Node.js\n\n```node\nconst sqlite3 = require('sqlite3').verbose()\nconst db = new sqlite3.Database('./sqlite3.db')\n\ndb.serialize(() =\u003e {\n  db.run('CREATE TABLE persons (name TEXT)')\n\n  const stmt = db.prepare('INSERT INTO persons VALUES (?)')\n  const names = ['alice', 'bob', 'charlie']\n  for (let i = 0; i \u003c names.length; i++) {\n    stmt.run(names[i])\n  }\n\n  stmt.finalize()\n\n  db.each('SELECT rowid AS id, name FROM persons', (err, row) =\u003e {\n    if (err) {\n      console.error(err)\n      return\n    }\n\n    console.log(row.id, row.name)\n  })\n})\n\ndb.close()\n```\n\nOutput\n\n```bash\n1 'alice'\n2 'bob'\n3 'charlie'\n```\n\n#### Go\n\n```go\npackage main\n\nimport (\n\t\"database/sql\"\n\t\"fmt\"\n\n\t_ \"github.com/mattn/go-sqlite3\"\n)\n\nfunc main() {\n\tdb, err := sql.Open(\"sqlite3\", \"./sqlite3.db\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer db.Close()\n\n\t_, err = db.Exec(\"CREATE TABLE persons (name TEXT)\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\ttx, err := db.Begin()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tstmt, err := tx.Prepare(\"INSERT INTO persons VALUES (?)\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer stmt.Close()\n\n\tnames := []string{\"alice\", \"bob\", \"charlie\"}\n\n\tfor _, name := range names {\n\t\t_, err := stmt.Exec(name)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\ttx.Commit()\n\n\trows, err := db.Query(\"SELECT rowid AS id, name FROM persons\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tvar id int\n\t\tvar name string\n\t\terr = rows.Scan(\u0026id, \u0026name)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tfmt.Println(id, name)\n\t}\n\n\terr = rows.Err()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n```\n\nOutput\n\n```bash\n1 alice\n2 bob\n3 charlie\n```\n\n**[⬆ back to top](#contents)**\n\n### testing\n---\n\n#### Node.js\n\n```node\nconst test = require('tape')\n\ntest(t =\u003e {\n  const tt = [\n\t\t{a:1, b:1, ret:2},\n\t\t{a:2, b:3, ret:5},\n\t\t{a:5, b:5, ret:10}\n  ]\n\n  t.plan(tt.length)\n\n  tt.forEach(tt =\u003e {\n    t.equal(sum(tt.a, tt.b), tt.ret)\n  })\n})\n\nfunction sum(a, b) {\n\treturn a + b\n}\n```\n\nOutput\n\n```bash\n$ node examples/example_test.js\nTAP version 13\n# (anonymous)\nok 1 should be equal\nok 2 should be equal\nok 3 should be equal\n\n1..3\n# tests 3\n# pass  3\n\n# ok\n```\n\n#### Go\n\n```go\npackage example\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc TestSum(t *testing.T) {\n\tfor _, tt := range []struct {\n\t\ta   int\n\t\tb   int\n\t\tret int\n\t}{\n\t\t{1, 1, 2},\n\t\t{2, 3, 5},\n\t\t{5, 5, 10},\n\t} {\n\t\tt.Run(fmt.Sprintf(\"(%v + %v)\", tt.a, tt.b), func(t *testing.T) {\n\t\t\tret := sum(tt.a, tt.b)\n\t\t\tif ret != tt.ret {\n\t\t\t\tt.Errorf(\"want %v, got %v\", tt.ret, ret)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc sum(a, b int) int {\n\treturn a + b\n}\n```\n\nOutput\n\n```bash\n$ go test -v examples/example_test.go\n=== RUN   TestSum\n=== RUN   TestSum/(1_+_1)\n=== RUN   TestSum/(2_+_3)\n=== RUN   TestSum/(5_+_5)\n--- PASS: TestSum (0.00s)\n    --- PASS: TestSum/(1_+_1) (0.00s)\n    --- PASS: TestSum/(2_+_3) (0.00s)\n    --- PASS: TestSum/(5_+_5) (0.00s)\nPASS\nok      command-line-arguments  0.008s\n```\n\n**[⬆ back to top](#contents)**\n\n### benchmarking\n---\n\n#### Node.js\n\n```node\nconst Benchmark = require('benchmark')\n\nconst suite = new Benchmark.Suite\nsuite.add('fib#recursion', () =\u003e {\n  fibRec(10)\n})\n.add('fib#loop', () =\u003e {\n  fibLoop(10)\n})\n.on('complete', () =\u003e {\n  console.log(suite[0].toString())\n  console.log(suite[1].toString())\n})\n.run({\n  async: true\n})\n\nfunction fibRec(n) {\n  if (n \u003c= 1) {\n    return n\n  }\n\n  return fibRec(n-1) + fibRec(n-2)\n}\n\nfunction fibLoop(n) {\n  let f = [0, 1]\n  for (let i = 2; i \u003c= n; i++) {\n    f[i] = f[i-1] + f[i-2]\n  }\n  return f[n]\n}\n```\n\nOutput\n\n```bash\n$ node examples/benchmark_test.js\nfib#recursion x 1,343,074 ops/sec ±1.26% (84 runs sampled)\nfib#loop x 20,104,517 ops/sec ±3.78% (78 runs sampled)\n```\n\n#### Go\n\n```go\npackage example\n\nimport (\n\t\"testing\"\n)\n\nfunc BenchmarkFibRec(b *testing.B) {\n\tfor n := 0; n \u003c b.N; n++ {\n\t\tfibRec(10)\n\t}\n}\n\nfunc BenchmarkFibLoop(b *testing.B) {\n\tfor n := 0; n \u003c b.N; n++ {\n\t\tfibLoop(10)\n\t}\n}\n\nfunc fibRec(n int) int {\n\tif n \u003c= 1 {\n\t\treturn n\n\t}\n\n\treturn fibRec(n-1) + fibRec(n-2)\n}\n\nfunc fibLoop(n int) int {\n\tf := make([]int, n+1, n+2)\n\tif n \u003c 2 {\n\t\tf = f[0:2]\n\t}\n\tf[0] = 0\n\tf[1] = 1\n\tfor i := 2; i \u003c= n; i++ {\n\t\tf[i] = f[i-1] + f[i-2]\n\t}\n\treturn f[n]\n}\n```\n\nOutput\n\n```bash\n$ go test -v -bench=. -benchmem examples/benchmark_test.go\ngoos: darwin\ngoarch: amd64\nBenchmarkFibRec-8        5000000               340 ns/op               0 B/op          0 allocs/op\nBenchmarkFibLoop-8      30000000                46.5 ns/op            96 B/op          1 allocs/op\nPASS\nok      command-line-arguments  3.502s\n```\n\n**[⬆ back to top](#contents)**\n\n### documentation\n---\n\n#### Node.js\n\n[jsdoc](http://usejsdoc.org/)\n\n```node\n/**\n * Creates a new Person.\n * @class\n * @example\n * const person = new Person('bob')\n */\nclass Person {\n  /**\n   * Create a person.\n   * @param {string} [name] - The person's name.\n   */\n  constructor(name) {\n    this.name = name\n  }\n\n  /**\n   * Get the person's name.\n   * @return {string} The person's name\n   * @example\n   * person.getName()\n   */\n  getName() {\n    return this.name\n  }\n\n  /**\n   * Set the person's name.\n   * @param {string} name - The person's name.\n   * @example\n   * person.setName('bob')\n   */\n  setName(name) {\n    this.name = name\n  }\n}\n```\n\n#### Go\n\n[godoc](https://blog.golang.org/examples)\n\n`person.go`\n\n```go\npackage person\n\nimport \"fmt\"\n\n// Person is the structure of a person\ntype Person struct {\n\tname string\n}\n\n// NewPerson creates a new person. Takes in a name argument.\nfunc NewPerson(name string) *Person {\n\treturn \u0026Person{\n\t\tname: name,\n\t}\n}\n\n// GetName returns the person's name\nfunc (p *Person) GetName() string {\n\treturn p.name\n}\n\n// SetName sets the person's name\nfunc (p *Person) SetName(name string) string {\n\treturn p.name\n}\n```\n\n`person_test.go`\n\n```go\n// Example of creating a new Person.\nfunc ExampleNewPerson() {\n\tperson := NewPerson(\"bob\")\n\t_ = person\n}\n\n// Example of getting person's name.\nfunc ExamplePerson_GetName() {\n\tperson := NewPerson(\"bob\")\n\tfmt.Println(person.GetName())\n\t// Output: bob\n}\n\n// Example of setting person's name.\nfunc ExamplePerson_SetName() {\n\tperson := NewPerson(\"alice\")\n\tperson.SetName(\"bob\")\n}\n```\n\n**[⬆ back to top](#contents)**\n\n\u003c!--\n### title\n---\n\n#### Node.js\n\n```node\n```\n\nOutput\n\n```bash\n```\n\n#### Go\n\n```go\n```\n\nOutput\n\n```bash\n```\n\n**[⬆ back to top](#contents)**\n--\u003e\n\n## Contributing\n\nPull requests are welcome!\n\nPlease submit a pull request for new interesting additions or for general content fixes.\n\nIf updating code, update both the README and the code in the [examples](examples/) folder.\n\n## License\n\nReleased under the [MIT](./LICENSE) license.\n\n© [Miguel Mota](https://github.com/miguelmota)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmiguelmota%2Fgolang-for-nodejs-developers","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmiguelmota%2Fgolang-for-nodejs-developers","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmiguelmota%2Fgolang-for-nodejs-developers/lists"}