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 theTour of Gotutorial. This guide is meant to be barely good enough to help you at a high level understand how to doXinYand doing further learning on your own is of course required.
- Examples
- comments
- printing
- logging
- variables
- types
- type check
- interpolation
- if/else
- for
- while
- switch
- arrays
- uint8 arrays
- array iteration
- buffers
- maps
- objects
- functions
- default values
- destructuring
- spread operator
- rest operator
- swapping
- classes
- generators
- datetime
- timeout
- interval
- IIFE
- files
- json
- big numbers
- promises
- async/await
- streams
- event emitter
- Contributing
- License
All sample code is available inexamples/
// this is a line comment
/*
this is a block comment
*/
packagemain
funcmain() {
// 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 stderr
packagemain
import(
"fmt"
"os"
)
funcmain() {
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 stderr
console.log((newDate()).toISOString(),'hello world')
Output
2021-04-11T20:55:07.451Z hello world
packagemain
import"log"
funcmain() {
log.Println("hello world")
}
Output
2021/04/11 13:55:07 hello world
(Packagelog
writes to standard error ánd prints the date and time of each logged message)
// function scoped
varfoo='foo'
// block scoped
letbar='bar'
// constant
constqux='qux'
(variables are block scoped in Go)
packagemain
funcmain() {
// explicit
varfoostring="foo"
// type inferred
varbar="foo"
// shorthand
baz:="bar"
// constant
constqux="qux"
}
constname='bob'
constage=21
constmessage=`${name}is${age}years old`
console.log(message)
Output
bob is 21 years old
packagemain
import"fmt"
funcmain() {
name:="bob"
age:=21
message:=fmt.Sprintf("%s is %d years old",name,age)
fmt.Println(message)
}
Output
bob is 21 years old
// primitives
constmyBool=true
constmyNumber=10
constmyString='foo'
constmySymbol=Symbol('bar')
constmyNull=null
constmyUndefined=undefined
// object types
constmyObject={}
constmyArray=[]
constmyFunction=function(){}
constmyError=newError('error')
constmyDate=newDate()
constmyRegex=/a/
constmyMap=newMap()
constmySet=newSet()
constmyPromise=Promise.resolve()
constmyGenerator=function*(){}
constmyClass=class{}
packagemain
funcmain() {
// primitives
varmyBoolbool=true
varmyIntint=10
varmyInt8int8=10
varmyInt16int16=10
varmyInt32int32=10
varmyInt64int64=10
varmyUintuint=10
varmyUint8uint8=10
varmyUint16uint16=10
varmyUint32uint32=10
varmyUint64uint64=10
varmyUintptruintptr=10
varmyFloat32float32=10.5
varmyFloat64float64=10.5
varmyComplex64complex64=-1+10i
varmyComplex128complex128=-1+10i
varmyStringstring="foo"
varmyBytebyte=10// alias to uint8
varmyRunerune='a'// alias to int32
// composite types
varmyStructstruct{}=struct{}{}
varmyArray[]string=[]string{}
varmyMapmap[string]int=map[string]int{}
varmyFunctionfunc()=func() {}
varmyChannelchanbool=make(chanbool)
varmyInterfaceinterface{}=nil
varmyPointer*int=new(int)
}
functiontypeOf(obj){
return{}.toString.call(obj).split(' ')[1].slice(0,-1).toLowerCase()
}
constvalues=[
true,
10,
'foo',
Symbol('bar'),
null,
undefined,
NaN,
{},
[],
function(){},
newError(),
newDate(),
/a/,
newMap(),
newSet(),
Promise.resolve(),
function*(){},
class{},
]
for(valueofvalues){
console.log(typeOf(value))
}
Output
boolean
number
string
symbol
null
undefined
number
object
array
function
error
date
regexp
map
set
promise
generatorfunction
function
packagemain
import(
"fmt"
"reflect"
"regexp"
"time"
)
funcmain() {
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(chanbool),
nil,
new(int),
time.Now(),
regexp.MustCompile(`^a$`),
}
for_,value:=rangevalues{
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.Regexp
constarray=[1,2]
if(array){
console.log('array exists')
}
if(array.length===2){
console.log('length is 2')
}elseif(array.length===1){
console.log('length is 1')
}else{
console.log('length is other')
}
constisOddLength=array.length%2==1?'yes':'no'
console.log(isOddLength)
Output
array exists
length is 2
no
packagemain
import"fmt"
funcmain() {
array:=[]byte{1,2}
ifarray!=nil{
fmt.Println("array exists")
}
iflen(array)==2{
fmt.Println("length is 2")
}elseiflen(array)==1{
fmt.Println("length is 1")
}else{
fmt.Println("length is other")
}
// closest thing to ternary operator
isOddLength:="no"
iflen(array)%2==1{
isOddLength="yes"
}
fmt.Println(isOddLength)
}
Output
array exists
length is 2
no
for(leti=0;i<=5;i++){
console.log(i)
}
Output
0
1
2
3
4
5
packagemain
import"fmt"
funcmain() {
fori:=0;i<=5;i++{
fmt.Println(i)
}
}
Output
0
1
2
3
4
5
leti=0
while(i<=5){
console.log(i)
i++
}
Output
0
1
2
3
4
5
(there's nowhilekeyword in Go but the same functionality is achieved by usingfor)
packagemain
import"fmt"
funcmain() {
i:=0
fori<=5{
fmt.Println(i)
i++
}
}
Output
0
1
2
3
4
5
constvalue='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 default
packagemain
import"fmt"
funcmain() {
value:="b"
switchvalue{
case"a":
fmt.Println("A")
case"b":
fmt.Println("B")
case"c":
fmt.Println("C")
default:
fmt.Println("first default")
}
switchvalue{
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 default
Examples of slicing, copying, appending, and prepending arrays.
constarray=[1,2,3,4,5]
console.log(array)
constclone=array.slice(0)
console.log(clone)
constsub=array.slice(2,4)
console.log(sub)
constconcatenated=clone.concat([6,7])
console.log(concatenated)
constprepended=[-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 ]
packagemain
import"fmt"
funcmain() {
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]
constarray=newUint8Array(10)
console.log(array)
constoffset=1
array.set([1,2,3],offset)
console.log(array)
constsub=array.subarray(2)
console.log(sub)
constsub2=array.subarray(2,4)
console.log(sub2)
console.log(array)
constvalue=9
conststart=5
constend=10
array.fill(value,start,end)
console.log(array)
console.log(array.byteLength)
Output
Uint8Array [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
Uint8Array [ 0, 1, 2, 3, 0, 0, 0, 0, 0, 0 ]
Uint8Array [ 2, 3, 0, 0, 0, 0, 0, 0 ]
Uint8Array [ 2, 3 ]
Uint8Array [ 0, 1, 2, 3, 0, 0, 0, 0, 0, 0 ]
Uint8Array [ 0, 1, 2, 3, 0, 9, 9, 9, 9, 9 ]
10
packagemain
import"fmt"
funcmain() {
array:=make([]uint8,10)
fmt.Println(array)
offset:=1
copy(array[offset:], []uint8{1,2,3})
fmt.Println(array)
sub:=array[2:]
fmt.Println(sub)
sub2:=array[2:4]
fmt.Println(sub2)
fmt.Println(array)
value:=uint8(9)
start:=5
end:=10
fori:=start;i<end;i++{
array[i]=value
}
fmt.Println(array)
fmt.Println(len(array))
}
Output
[0 0 0 0 0 0 0 0 0 0]
[0 1 2 3 0 0 0 0 0 0]
[2 3 0 0 0 0 0 0]
[2 3]
[0 1 2 3 0 0 0 0 0 0]
[0 1 2 3 0 9 9 9 9 9]
10
Examples of iterating, mapping, filtering, and reducing arrays.
constarray=['a','b','c']
array.forEach((value,i)=>{
console.log(i,value)
})
constmapped=array.map(value=>{
returnvalue.toUpperCase()
})
console.log(mapped)
constfiltered=array.filter((value,i)=>{
returni%2==0
})
console.log(filtered)
constreduced=array.reduce((acc,value,i)=>{
if(i%2==0){
acc.push(value.toUpperCase())
}
returnacc
},[])
console.log(reduced)
Output
0'a'
1'b'
2'c'
['A','B','C']
['a','c']
['A','C']
packagemain
import(
"fmt"
"strings"
)
funcmain() {
array:=[]string{"a","b","c"}
fori,value:=rangearray{
fmt.Println(i,value)
}
mapped:=make([]string,len(array))
fori,value:=rangearray{
mapped[i]=strings.ToUpper(value)
}
fmt.Println(mapped)
varfiltered[]string
fori,value:=rangearray{
ifi%2==0{
filtered=append(filtered,value)
}
}
fmt.Println(filtered)
varreduced[]string
fori,value:=rangearray{
ifi%2==0{
reduced=append(reduced,strings.ToUpper(value))
}
}
fmt.Println(reduced)
}
Output
0 a
1 b
2 c
[A B C]
[a c]
[A C]
Examples of how to sort an array
conststringArray=['a','d','z','b','c','y']
conststringArraySortedAsc=stringArray.sort((a,b)=>a>b?1:-1)
console.log(stringArraySortedAsc)
conststringArraySortedDesc=stringArray.sort((a,b)=>a>b?-1:1)
console.log(stringArraySortedDesc)
constnumberArray=[1,3,5,9,4,2,0]
constnumberArraySortedAsc=numberArray.sort((a,b)=>a-b)
console.log(numberArraySortedAsc)
constnumberArraySortedDesc=numberArray.sort((a,b)=>b-a)
console.log(numberArraySortedDesc)
constcollection=[
{
name:"Li L",
age:8
},
{
name:"Json C",
age:3
},
{
name:"Zack W",
age:15
},
{
name:"Yi M",
age:2
}
]
constcollectionSortedByAgeAsc=collection.sort((a,b)=>a.age-b.age)
console.log(collectionSortedByAgeAsc)
constcollectionSortedByAgeDesc=collection.sort((a,b)=>b.age-a.age)
console.log(collectionSortedByAgeDesc)
Output
['a','b','c','d','y','z']
['z','y','d','c','b','a']
[ 0, 1, 2, 3, 4, 5, 9 ]
[ 9, 5, 4, 3, 2, 1, 0 ]
[ { name:'Yi M',age: 2 },
{ name:'Json C',age: 3 },
{ name:'Li L',age: 8 },
{ name:'Zack W',age: 15 } ]
[ { name:'Zack W',age: 15 },
{ name:'Li L',age: 8 },
{ name:'Json C',age: 3 },
{ name:'Yi M',age: 2 } ]
packagemain
import(
"fmt"
"sort"
)
typePersonstruct{
Namestring
Ageint
}
typePersonCollection[]Person
func(pcPersonCollection)Len()int{
returnlen(pc)
}
func(pcPersonCollection)Swap(i,jint) {
pc[i],pc[j]=pc[j],pc[i]
}
func(pcPersonCollection)Less(i,jint)bool{
// asc
returnpc[i].Age<pc[j].Age
}
funcmain() {
intList:=[]int{1,3,5,9,4,2,0}
// asc
sort.Ints(intList)
fmt.Println(intList)
// desc
sort.Sort(sort.Reverse(sort.IntSlice(intList)))
fmt.Println(intList)
stringList:=[]string{"a","d","z","b","c","y"}
// asc
sort.Strings(stringList)
fmt.Println(stringList)
// desc
sort.Sort(sort.Reverse(sort.StringSlice(stringList)))
fmt.Println(stringList)
collection:=[]Person{
{"Li L",8},
{"Json C",3},
{"Zack W",15},
{"Yi M",2},
}
// asc
sort.Sort(PersonCollection(collection))
fmt.Println(collection)
// desc
sort.Sort(sort.Reverse(PersonCollection(collection)))
fmt.Println(collection)
}
Output
[0 1 2 3 4 5 9]
[9 5 4 3 2 1 0]
[a b c d y z]
[z y d c b a]
[{Yi M 2} {Json C 3} {Li L 8} {Zack W 15}]
[{Zack W 15} {Li L 8} {Json C 3} {Yi M 2}]
Examples of how to allocate a buffer, write in big or little endian format, encode to a hex string, and check if buffers are equal.
constbuf=Buffer.alloc(6)
letvalue=0x1234567890ab
letoffset=0
letbyteLength=6
buf.writeUIntBE(value,offset,byteLength)
lethexstr=buf.toString('hex')
console.log(hexstr)
constbuf2=Buffer.alloc(6)
value=0x1234567890ab
offset=0
byteLength=6
buf2.writeUIntLE(value,offset,byteLength)
hexstr=buf2.toString('hex')
console.log(hexstr)
letisEqual=Buffer.compare(buf,buf2)===0
console.log(isEqual)
isEqual=Buffer.compare(buf,buf)===0
console.log(isEqual)
Output
1234567890ab
ab9078563412
false
true
packagemain
import(
"bytes"
"encoding/binary"
"encoding/hex"
"fmt"
"log"
"math/big"
"reflect"
)
funcwriteUIntBE(buffer[]byte,value,offset,byteLengthint64) {
slice:=make([]byte,byteLength)
val:=new(big.Int)
val.SetUint64(uint64(value))
valBytes:=val.Bytes()
buf:=bytes.NewBuffer(slice)
err:=binary.Write(buf,binary.BigEndian,&valBytes)
iferr!=nil{
log.Fatal(err)
}
slice=buf.Bytes()
slice=slice[int64(len(slice))-byteLength:len(slice)]
copy(buffer[offset:],slice)
}
funcwriteUIntLE(buffer[]byte,value,offset,byteLengthint64) {
slice:=make([]byte,byteLength)
val:=new(big.Int)
val.SetUint64(uint64(value))
valBytes:=val.Bytes()
tmp:=make([]byte,len(valBytes))
fori:=rangevalBytes{
tmp[i]=valBytes[len(valBytes)-1-i]
}
copy(slice,tmp)
copy(buffer[offset:],slice)
}
funcmain() {
buf:=make([]byte,6)
writeUIntBE(buf,0x1234567890ab,0,6)
fmt.Println(hex.EncodeToString(buf))
buf2:=make([]byte,6)
writeUIntLE(buf2,0x1234567890ab,0,6)
fmt.Println(hex.EncodeToString(buf2))
isEqual:=reflect.DeepEqual(buf,buf2)
fmt.Println(isEqual)
isEqual=reflect.DeepEqual(buf,buf)
fmt.Println(isEqual)
}
Output
1234567890ab
ab9078563412
false
true
constmap=newMap()
map.set('foo','bar')
letfound=map.has('foo')
console.log(found)
letitem=map.get('foo')
console.log(item)
map.delete('foo')
found=map.has('foo')
console.log(found)
item=map.get('foo')
console.log(item)
constmap2={}
map2['foo']='bar'
item=map2['foo']
deletemap2['foo']
constmap3=newMap()
map3.set('foo',100)
map3.set('bar',200)
map3.set('baz',300)
for(let[key,value]ofmap3){
console.log(key,value)
}
Output
true
bar
false
undefined
foo 100
bar 200
baz 300
packagemain
import"fmt"
funcmain() {
map1:=make(map[string]string)
map1["foo"]="bar"
item,found:=map1["foo"]
fmt.Println(found)
fmt.Println(item)
delete(map1,"foo")
item,found=map1["foo"]
fmt.Println(found)
fmt.Println(item)
map2:=make(map[string]int)
map2["foo"]=100
map2["bar"]=200
map2["baz"]=300
forkey,value:=rangemap2{
fmt.Println(key,value)
}
}
Output
true
bar
false
foo 100
bar 200
baz 300
constobj={
someProperties:{
'foo':'bar'
},
someMethod:(prop)=>{
returnobj.someProperties[prop]
}
}
letitem=obj.someProperties['foo']
console.log(item)
item=obj.someMethod('foo')
console.log(item)
Output
bar
bar
packagemain
import"fmt"
typeObjstruct{
SomePropertiesmap[string]string
}
funcNewObj()*Obj{
return&Obj{
SomeProperties:map[string]string{
"foo":"bar",
},
}
}
func(o*Obj)SomeMethod(propstring)string{
returno.SomeProperties[prop]
}
funcmain() {
obj:=NewObj()
item:=obj.SomeProperties["foo"]
fmt.Println(item)
item=obj.SomeMethod("foo")
fmt.Println(item)
}
Output
bar
bar
functionadd(a,b){
returna+b
}
constresult=add(2,3)
console.log(result)
Output
5
packagemain
import"fmt"
funcadd(aint,bint)int{
returna+b
}
funcmain() {
result:=add(2,3)
fmt.Println(result)
}
Output
5
functiongreet(name='stranger'){
return`hello${name}`
}
letmessage=greet()
console.log(message)
message=greet('bob')
console.log(message)
Output
hello stranger
hello bob
use pointers and check for nil to know if explicitly left blank
packagemain
import"fmt"
funcgreet(name*string)string{
n:="stranger"
ifname!=nil{
n=*name
}
returnfmt.Sprintf("hello %s",n)
}
funcmain() {
message:=greet(nil)
fmt.Println(message)
name:="bob"
message=greet(&name)
fmt.Println(message)
}
Output
hello stranger
hello bob
constobj={key:'foo',value:'bar'}
const{key,value}=obj
console.log(key,value)
Output
foo bar
packagemain
import"fmt"
typeObjstruct{
Keystring
Valuestring
}
func(o*Obj)Read() (string,string) {
returno.Key,o.Value
}
funcmain() {
obj:=Obj{
Key:"foo",
Value:"bar",
}
// option 1: multiple variable assignment
key,value:=obj.Key,obj.Value
fmt.Println(key,value)
// option 2: return multiple values from a function
key,value=obj.Read()
fmt.Println(key,value)
}
Output
foo bar
foo bar
constarray=[1,2,3,4,5]
console.log(...array)
Output
1 2 3 4 5
packagemain
import"fmt"
funcmain() {
array:=[]byte{1,2,3,4,5}
vari[]interface{}
for_,value:=rangearray{
i=append(i,value)
}
fmt.Println(i...)
}
Output
1 2 3 4 5
functionsum(...nums){
lett=0
for(letnofnums){
t+=n
}
returnt
}
consttotal=sum(1,2,3,4,5)
console.log(total)
Output
15
packagemain
import"fmt"
funcsum(nums...int)int{
vartint
for_,n:=rangenums{
t+=n
}
returnt
}
funcmain() {
total:=sum(1,2,3,4,5)
fmt.Println(total)
}
Output
15
leta='foo'
letb='bar'
console.log(a,b);
[b,a]=[a,b]
console.log(a,b)
Output
foo bar
bar foo
packagemain
import"fmt"
funcmain() {
a:="foo"
b:="bar"
fmt.Println(a,b)
b,a=a,b
fmt.Println(a,b)
}
Output
foo bar
bar foo
Examples of classes, constructors, instantiation, and "this" keyword.
classFoo{
constructor(value){
this.item=value
}
getItem(){
returnthis.item
}
setItem(value){
this.item=value
}
}
constfoo=newFoo('bar')
console.log(foo.item)
foo.setItem('qux')
constitem=foo.getItem()
console.log(item)
Output
bar
qux
(closest thing to a class is to use a structure)
packagemain
import"fmt"
typeFoostruct{
Itemstring
}
funcNewFoo(valuestring)*Foo{
return&Foo{
Item:value,
}
}
func(f*Foo)GetItem()string{
returnf.Item
}
func(f*Foo)SetItem(valuestring) {
f.Item=value
}
funcmain() {
foo:=NewFoo("bar")
fmt.Println(foo.Item)
foo.SetItem("qux")
item:=foo.GetItem()
fmt.Println(item)
}
Output
bar
qux
function*generator(){
yield'hello'
yield'world'
}
letgen=generator()
while(true){
let{value,done}=gen.next()
console.log(value,done)
if(done){
break
}
}
// alternatively
for(letvalueofgenerator()){
console.log(value)
}
Output
hellofalse
worldfalse
undefinedtrue
hello
world
packagemain
import"fmt"
funcGenerator()chanstring{
c:=make(chanstring)
gofunc() {
c<-"hello"
c<-"world"
close(c)
}()
returnc
}
funcGeneratorFunc()func() (string,bool) {
s:=[]string{"hello","world"}
i:=-1
returnfunc() (string,bool) {
i++
ifi>=len(s) {
return"",false
}
returns[i],true
}
}
funcmain() {
gen:=Generator()
for{
value,more:=<-gen
fmt.Println(value,more)
if!more{
break
}
}
// alternatively
forvalue:=rangeGenerator() {
fmt.Println(value)
}
// alternatively
genfn:=GeneratorFunc()
for{
value,more:=genfn()
fmt.Println(value,more)
if!more{
break
}
}
}
Output
hellotrue
worldtrue
false
hello
world
hellotrue
worldtrue
false
Examples of parsing, formatting, and getting unix timestamp of dates.
constnowUnix=Date.now()
console.log(nowUnix)
constdatestr='2019-01-17T09:24:23+00:00'
constdate=newDate(datestr)
console.log(date.getTime())
console.log(date.toString())
constfutureDate=newDate(date)
futureDate.setDate(date.getDate()+14)
console.log(futureDate.toString())
constformatted=`${String(date.getMonth()+1).padStart(2,0)}/${String(date.getDate()).padStart(2,0)}/${date.getFullYear()}`
console.log(formatted)
Output
1547718844168
1547717063000
Thu Jan 17 2019 01:24:23 GMT-0800 (Pacific Standard Time)
Thu Jan 31 2019 01:24:23 GMT-0800 (Pacific Standard Time)
01/17/2019
packagemain
import(
"fmt"
"time"
)
funcmain() {
nowUnix:=time.Now().Unix()
fmt.Println(nowUnix)
datestr:="2019-01-17T09:24:23+00:00"
date,err:=time.Parse("2006-01-02T15:04:05Z07:00",datestr)
iferr!=nil{
panic(err)
}
fmt.Println(date.Unix())
fmt.Println(date.String())
futureDate:=date.AddDate(0,0,14)
fmt.Println(futureDate.String())
formatted:=date.Format("01/02/2006")
fmt.Println(formatted)
}
Output
1547718844
1547717063
2019-01-17 09:24:23 +0000 +0000
2019-01-31 09:24:23 +0000 +0000
01/17/2019
setTimeout(callback,1e3)
functioncallback(){
console.log('called')
}
Output
called
packagemain
import(
"fmt"
"sync"
"time"
)
varwgsync.WaitGroup
funccallback() {
deferwg.Done()
fmt.Println("called")
}
funcmain() {
wg.Add(1)
time.AfterFunc(1*time.Second,callback)
wg.Wait()
}
Output
called
leti=0
constid=setInterval(callback,1e3)
functioncallback(){
console.log('called',i)
if(i===3){
clearInterval(id)
}
i++
}
Output
called 0
called 1
called 2
called 3
packagemain
import(
"fmt"
"time"
)
funccallback(iint) {
fmt.Println("called",i)
}
funcmain() {
ticker:=time.NewTicker(1*time.Second)
i:=0
forrangeticker.C{
callback(i)
ifi==3{
ticker.Stop()
break
}
i++
}
}
Output
called 0
called 1
called 2
called 3
Immediately invoked function expression
(function(name){
console.log('hello',name)
})('bob')
Output
hello bob
packagemain
import"fmt"
funcmain() {
func(namestring) {
fmt.Println("hello",name)
}("bob")
}
Output
hello bob
Examples of creating, opening, writing, reading, closing, and deleting files.
constfs=require('fs')
// create file
fs.closeSync(fs.openSync('test.txt','w'))
// open file (returns file descriptor)
constfd=fs.openSync('test.txt','r+')
letwbuf=Buffer.from('hello world.')
letrbuf=Buffer.alloc(12)
letoff=0
letlen=12
letpos=0
// write file
fs.writeSync(fd,wbuf,pos)
// read file
fs.readSync(fd,rbuf,off,len,pos)
console.log(rbuf.toString())
// close file
fs.closeSync(fd)
// delete file
fs.unlinkSync('test.txt')
Output
hello world.
packagemain
import(
"fmt"
"os"
"syscall"
)
funcmain() {
// create file
file,err:=os.Create("test.txt")
iferr!=nil{
panic(err)
}
// close file
file.Close()
// open file
file,err=os.OpenFile("test.txt",os.O_RDWR,0755)
iferr!=nil{
panic(err)
}
// file descriptor
fd:=file.Fd()
// open file (using file descriptor)
file=os.NewFile(fd,"test file")
wbuf:=[]byte("hello world.")
rbuf:=make([]byte,12)
varoffint64
// write file
if_,err:=file.WriteAt(wbuf,off);err!=nil{
panic(err)
}
// read file
if_,err:=file.ReadAt(rbuf,off);err!=nil{
panic(err)
}
fmt.Println(string(rbuf))
// close file (using file descriptor)
iferr:=syscall.Close(int(fd));err!=nil{
panic(err)
}
// delete file
iferr:=os.Remove("test.txt");err!=nil{
panic(err)
}
}
Output
hello world.
Examples of how to parse (unmarshal) and stringify (marshal) JSON.
letjsonstr='{ "foo": "bar" }'
letparsed=JSON.parse(jsonstr)
console.log(parsed)
jsonstr=JSON.stringify(parsed)
console.log(jsonstr)
Output
{ foo:'bar'}
{"foo":"bar"}
packagemain
import(
"encoding/json"
"fmt"
)
typeTstruct{
Foostring`json: "foo" `
}
funcmain() {
jsonstr:=`{ "foo": "bar" }`
t:=new(T)
err:=json.Unmarshal([]byte(jsonstr),t)
iferr!=nil{
panic(err)
}
fmt.Println(t)
marshalled,err:=json.Marshal(t)
jsonstr=string(marshalled)
fmt.Println(jsonstr)
}
Output
&{bar}
{"foo":"bar"}
Examples of creating big number types from and to uint, string, hex, and buffers.
letbn=75n;
console.log(bn.toString(10))
bn=BigInt('75')
console.log(bn.toString(10))
bn=BigInt(0x4b)
console.log(bn.toString(10))
bn=BigInt('0x4b')
console.log(bn.toString(10))
bn=BigInt('0x'+Buffer.from('4b','hex').toString('hex'))
console.log(bn.toString(10))
console.log(Number(bn))
console.log(bn.toString(16))
console.log(Buffer.from(bn.toString(16),'hex'))
letbn2=BigInt(100)
letisEqual=bn===bn2
console.log(isEqual)
letisGreater=bn>bn2
console.log(isGreater)
letisLesser=bn<bn2
console.log(isLesser)
Output
75
75
75
75
75
75
4b
<Buffer 4b>
false
false
true
packagemain
import(
"encoding/hex"
"fmt"
"math/big"
)
funcmain() {
bn:=new(big.Int)
bn.SetUint64(75)
fmt.Println(bn.String())
bn=new(big.Int)
bn.SetString("75",10)
fmt.Println(bn.String())
bn=new(big.Int)
bn.SetUint64(0x4b)
fmt.Println(bn.String())
bn=new(big.Int)
bn.SetString("4b",16)
fmt.Println(bn.String())
bn=new(big.Int)
bn.SetBytes([]byte{0x4b})
fmt.Println(bn.String())
fmt.Println(bn.Uint64())
fmt.Println(hex.EncodeToString(bn.Bytes()))
fmt.Println(bn.Bytes())
bn2:=big.NewInt(100)
isEqual:=bn.Cmp(bn2)==0
fmt.Println(isEqual)
isGreater:=bn.Cmp(bn2)==1
fmt.Println(isGreater)
isLesser:=bn.Cmp(bn2)==-1
fmt.Println(isLesser)
}
Output
75
75
75
75
75
75
4b
[75]
false
false
true
functionasyncMethod(value){
returnnewPromise((resolve,reject)=>{
setTimeout(()=>{
resolve('resolved: '+value)
},1e3)
})
}
functionmain(){
asyncMethod('foo')
.then(result=>console.log(result))
.catch(err=>console.error(err))
Promise.all([
asyncMethod('A'),
asyncMethod('B'),
asyncMethod('C')
])
.then(result=>console.log(result))
.catch(err=>console.error(err))
}
main()
Output
resolved: foo
['resolved: A','resolved: B','resolved: C']
(closest thing is to use channels)
packagemain
import(
"fmt"
"sync"
"time"
"github /prometheus/common/log"
)
funcasyncMethod(valuestring)chaninterface{} {
ch:=make(chaninterface{},1)
gofunc() {
time.Sleep(1*time.Second)
ch<-"resolved:"+value
close(ch)
}()
returnch
}
funcresolveAll(ch...chaninterface{})chaninterface{} {
varwgsync.WaitGroup
res:=make([]string,len(ch))
resCh:=make(chaninterface{},1)
gofunc() {
fori,c:=rangech{
wg.Add(1)
gofunc(jint,ifcChchaninterface{}) {
ifc:=<-ifcCh
switchv:=ifc.(type) {
caseerror:
resCh<-v
casestring:
res[j]=v
}
wg.Done()
}(i,c)
}
wg.Wait()
resCh<-res
close(resCh)
}()
returnresCh
}
funcmain() {
varwgsync.WaitGroup
wg.Add(2)
gofunc() {
result:=<-asyncMethod("foo")
switchv:=result.(type) {
casestring:
fmt.Println(v)
caseerror:
log.Errorln(v)
}
wg.Done()
}()
gofunc() {
result:=<-resolveAll(
asyncMethod("A"),
asyncMethod("B"),
asyncMethod("C"),
)
switchv:=result.(type) {
case[]string:
fmt.Println(v)
caseerror:
log.Errorln(v)
}
wg.Done()
}()
wg.Wait()
}
Output
resolved: foo
[resolved: A resolved: B resolved: C]
functionhello(name){
returnnewPromise((resolve,reject)=>{
setTimeout(()=>{
if(name==='fail'){
reject(newError('failed'))
}else{
resolve('hello '+name)
}
},1e3)
})
}
asyncfunctionmain(){
try{
letoutput=awaithello('bob')
console.log(output)
output=awaithello('fail')
console.log(output)
}catch(err){
console.log(err.message)
}
}
main()
Output
hello bob
failed
(closest thing is to use channels)
packagemain
import(
"errors"
"fmt"
"time"
"github /prometheus/common/log"
)
funchello(namestring)chaninterface{} {
ch:=make(chaninterface{},1)
gofunc() {
time.Sleep(1*time.Second)
ifname=="fail"{
ch<-errors.New("failed")
}else{
ch<-"hello"+name
}
}()
returnch
}
funcmain() {
result:=<-hello("bob")
switchv:=result.(type) {
casestring:
fmt.Println(v)
caseerror:
log.Errorln(v)
}
result=<-hello("fail")
switchv:=result.(type) {
casestring:
fmt.Println(v)
caseerror:
log.Errorln(v)
}
}
Output
hello bob
failed
Examples of reading and writing streams
const{Readable,Writable}=require('stream')
constinStream=newReadable()
inStream.push(Buffer.from('foo'))
inStream.push(Buffer.from('bar'))
inStream.push(null)// end stream
inStream.pipe(process.stdout)
constoutStream=newWritable({
write(chunk,encoding,callback){
console.log('received: '+chunk.toString('utf8'))
callback()
}
})
outStream.write(Buffer.from('abc'))
outStream.write(Buffer.from('xyz'))
outStream.end()
Output
foobar
received: abc
received: xyz
packagemain
import(
"bufio"
"bytes"
"fmt"
"io"
"os"
"runtime"
)
funcmain() {
inStream:=new(bytes.Buffer)
w:=bufio.NewWriter(inStream)
_,err:=w.Write([]byte("foo"))
iferr!=nil{
panic(err)
}
_,err=w.Write([]byte("bar"))
iferr!=nil{
panic(err)
}
err=w.Flush()
iferr!=nil{
panic(err)
}
inStream.WriteTo(os.Stdout)
fmt.Print("\n")
outStream:=new(bytes.Buffer)
outStream.Write([]byte("abc\n"))
outStream.Write([]byte("xyc\n"))
piper,pipew:=io.Pipe()
gofunc() {
sc:=bufio.NewScanner(piper)
forsc.Scan() {
fmt.Println("received:"+sc.Text())
}
iferr:=sc.Err();err!=nil{
panic(err)
}
os.Exit(0)
}()
gofunc() {
deferpipew.Close()
io.Copy(pipew,outStream)
}()
deferruntime.Goexit()
}
Output
foobar
received: abc
received: xyc
constEventEmitter=require('events')
classMyEmitterextendsEventEmitter{}
constmyEmitter=newMyEmitter()
myEmitter.on('my-event',msg=>{
console.log(msg)
})
myEmitter.on('my-other-event',msg=>{
console.log(msg)
})
myEmitter.emit('my-event','hello world')
myEmitter.emit('my-other-event','hello other world')
Output
hello world
hello other world
(closest thing is to use channels)
packagemain
import(
"fmt"
)
typeMyEmittermap[string]chanstring
funcmain() {
myEmitter:=MyEmitter{}
myEmitter["my-event"]=make(chanstring)
myEmitter["my-other-event"]=make(chanstring)
gofunc() {
for{
select{
casemsg:=<-myEmitter["my-event"]:
fmt.Println(msg)
casemsg:=<-myEmitter["my-other-event"]:
fmt.Println(msg)
}
}
}()
myEmitter["my-event"]<-"hello world"
myEmitter["my-other-event"]<-"hello other world"
}
Output
hello world
hello other world
consterr1=newError('some error')
console.log(err1)
classFooErrorextendsError{
constructor(message){
super(message)
this.name='FooError'
this.message=message
}
toString(){
returnthis.message
}
}
consterr2=newFooError('my custom error')
console.log(err2)
Output
Error: some error
{ FooError: my custom error }
packagemain
import(
"errors"
"fmt"
)
typeFooErrorstruct{
sstring
}
func(f*FooError)Error()string{
returnf.s
}
funcNewFooError(sstring)error{
return&FooError{s}
}
funcmain() {
err1:=errors.New("some error")
fmt.Println(err1)
err2:=NewFooError("my custom error")
fmt.Println(err2)
}
Output
some error
my custom error
functionfoo(fail){
if(fail){
throwError('my error')
}
}
functionmain(){
try{
foo(true)
}catch(err){
console.log(`caught error:${err.message}`)
}
}
main()
Output
caught error: my error
packagemain
import(
"errors"
"fmt"
)
funcfoo(failbool)error{
iffail{
returnerrors.New("my error")
}
returnnil
}
funcmain() {
err:=foo(true)
iferr!=nil{
fmt.Printf("caught error: %s\n",err.Error())
}
}
Output
caught error: my error
functionfoo(){
throwError('my exception')
}
functionmain(){
foo()
}
process.on('uncaughtException',err=>{
console.log(`caught exception:${err.message}`)
process.exit(1)
})
main()
Output
caught exception: my exception
packagemain
import(
"fmt"
)
funcfoo() {
panic("my exception")
}
funcmain() {
deferfunc() {
ifr:=recover();r!=nil{
fmt.Printf("caught exception: %s",r)
}
}()
foo()
}
Output
caught exception: my exception
letinput='foobar'
letreplaced=input.replace(/foo(.*)/i,'qux$1')
console.log(replaced)
letmatch=/o{2}/i.test(input)
console.log(match)
input='111-222-333'
letmatches=input.match(/([0-9]+)/gi)
console.log(matches)
Output
quxbar
true
['111','222','333']
packagemain
import(
"fmt"
"regexp"
)
funcmain() {
input:="foobar"
re:=regexp.MustCompile(`(?i)foo(.*)`)
replaced:=re.ReplaceAllString(input,"qux$1")
fmt.Println(replaced)
re=regexp.MustCompile(`(?i)o{2}`)
match:=re.Match([]byte(input))
fmt.Println(match)
input="111-222-333"
re=regexp.MustCompile(`(?i)([0-9]+)`)
matches:=re.FindAllString(input,-1)
fmt.Println(matches)
}
Output
quxbar
true
[111 222 333]
const{execSync}=require('child_process')
constoutput=execSync(`echo 'hello world'`)
console.log(output.toString())
Output
hello world
packagemain
import(
"fmt"
"os/exec"
)
funcmain() {
output,err:=exec.Command("echo","hello world").Output()
iferr!=nil{
panic(err)
}
fmt.Println(string(output))
}
Output
hello world
const{exec}=require('child_process')
exec(`echo 'hello world'`,(error,stdout,stderr)=>{
if(error){
console.error(err)
}
if(stderr){
console.error(stderr)
}
if(stdout){
console.log(stdout)
}
})
Output
hello world
packagemain
import(
"os"
"os/exec"
)
funcmain() {
cmd:=exec.Command("echo","hello world")
cmd.Stdout=os.Stdout
cmd.Stderr=os.Stderr
cmd.Run()
}
Output
hello world
constnet=require('net')
functionhandler(socket){
socket.write('Received: ')
socket.pipe(socket)
}
constserver=net.createServer(handler)
server.listen(3000)
Output
$echo'hello'|nc localhost 3000
Received: hello
packagemain
import(
"bufio"
"net"
)
funchandler(connnet.Conn) {
deferconn.Close()
reader:=bufio.NewReader(conn)
for{
message,err:=reader.ReadString('\n')
iferr!=nil{
return
}
conn.Write([]byte("Received:"))
conn.Write([]byte(message))
}
}
funcmain() {
listener,err:=net.Listen("tcp",":3000")
iferr!=nil{
panic(err)
}
deferlistener.Close()
for{
conn,err:=listener.Accept()
iferr!=nil{
panic(err)
}
gohandler(conn)
}
}
Output
$echo'hello'|nc localhost 3000
Received: hello
constdgram=require('dgram')
constserver=dgram.createSocket('udp4')
server.on('error',err=>{
console.error(err)
server.close()
})
server.on('message',(msg,rinfo)=>{
constdata=msg.toString('utf8').trim()
console.log(`received:${data}from${rinfo.address}:${rinfo.port}`)
})
server.on('listening',()=>{
constaddress=server.address()
console.log(`server listening${address.address}:${address.port}`)
})
server.bind(3000)
Output
$echo'hello world'>/dev/udp/0.0.0.0/3000
server listening 0.0.0.0:3000
received: hello world from 127.0.0.1:51452
packagemain
import(
"fmt"
"net"
"strings"
)
funcmain() {
conn,err:=net.ListenUDP("udp",&net.UDPAddr{
Port:3000,
IP:net.ParseIP("0.0.0.0"),
})
iferr!=nil{
panic(err)
}
deferconn.Close()
fmt.Printf("server listening %s\n",conn.LocalAddr().String())
for{
message:=make([]byte,20)
rlen,remote,err:=conn.ReadFromUDP(message[:])
iferr!=nil{
panic(err)
}
data:=strings.TrimSpace(string(message[:rlen]))
fmt.Printf("received: %s from %s\n",data,remote)
}
}
Output
$echo'hello world'>/dev/udp/0.0.0.0/3000
server listening [::]:3000
received: hello world from 127.0.0.1:50275
consthttp=require('http')
functionhandler(request,response){
response.writeHead(200,{'Content-type':'text/plain'})
response.write('hello world')
response.end()
}
constserver=http.createServer(handler)
server.listen(8080)
Output
$ curl http://localhost:8080
hello world
packagemain
import(
"net/http"
)
funchandler(whttp.ResponseWriter,r*http.Request) {
w.WriteHeader(200)
w.Write([]byte("hello world"))
}
funcmain() {
http.HandleFunc("/",handler)
iferr:=http.ListenAndServe(":8080",nil);err!=nil{
panic(err)
}
}
Output
$ curl http://localhost:8080
hello world
consturl=require('url')
constqs=require('querystring')
consturlstr='http://bob:[email protected]:8080/somepath?foo=bar'
constparsed=url.parse(urlstr)
console.log(parsed.protocol)
console.log(parsed.auth)
console.log(parsed.port)
console.log(parsed.hostname)
console.log(parsed.pathname)
console.log(qs.parse(parsed.search.substr(1)))
Output
http:
bob:secret
8080
sub.example
/somepath
{ foo:'bar'}
packagemain
import(
"fmt"
"net/url"
)
funcmain() {
urlstr:="http://bob:[email protected]:8080/somepath?foo=bar"
u,err:=url.Parse(urlstr)
iferr!=nil{
panic(err)
}
fmt.Println(u.Scheme)
fmt.Println(u.User)
fmt.Println(u.Port())
fmt.Println(u.Hostname())
fmt.Println(u.Path)
fmt.Println(u.Query())
}
Output
http
bob:secret
8080
sub.example
/somepath
map[foo:[bar]]
constzlib=require('zlib')
constdata=Buffer.from('hello world','utf-8')
zlib.gzip(data,(err,compressed)=>{
if(err){
console.error(err)
}
console.log(compressed)
zlib.unzip(compressed,(err,decompressed)=>{
if(err){
console.error(err)
}
console.log(decompressed.toString())
})
})
Output
<Buffer 1f 8b 08 00 00 00 00 00 00 13 cb 48cdc9 c9 57 28 cf 2f ca 49 01 00 85 11 4a 0d 0b 00 0000>
hello world
packagemain
import(
"bytes"
"compress/gzip"
"fmt"
)
funcmain() {
data:=[]byte("hello world")
compressed:=new(bytes.Buffer)
w:=gzip.NewWriter(compressed)
if_,err:=w.Write(data);err!=nil{
panic(err)
}
iferr:=w.Close();err!=nil{
panic(err)
}
fmt.Println(compressed.Bytes())
decompressed:=new(bytes.Buffer)
r,err:=gzip.NewReader(compressed)
iferr!=nil{
panic(err)
}
_,err=decompressed.ReadFrom(r)
iferr!=nil{
panic(err)
}
fmt.Println(string(decompressed.Bytes()))
}
Output
[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]
hello world
DNS lookup examples
constdns=require('dns')
dns.resolveNs('google ',(err,ns)=>{
if(err){
console.error(err)
}
console.log(ns)
})
dns.resolve4('google ',(err,ips)=>{
if(err){
console.error(err)
}
console.log(ips)
})
dns.resolveMx('google ',(err,mx)=>{
if(err){
console.error(err)
}
console.log(mx)
})
dns.resolveTxt('google ',(err,txt)=>{
if(err){
console.error(err)
}
console.log(txt)
})
dns.setServers(['1.1.1.1'])
console.log(dns.getServers())
dns.resolveNs('google ',(err,ns)=>{
if(err){
console.error(err)
}
console.log(ns)
})
Output
[
'ns2.google',
'ns3.google',
'ns4.google',
'ns1.google'
]
['172.217.11.78']
[ { exchange:'alt4.aspmx.l.google',priority: 50 },
{ exchange:'alt2.aspmx.l.google',priority: 30 },
{ exchange:'alt3.aspmx.l.google',priority: 40 },
{ exchange:'aspmx.l.google',priority: 10 },
{ exchange:'alt1.aspmx.l.google',priority: 20 } ]
[ ['v=spf1 include:_spf.google ~all'],
['docusign=05958488-4752-4ef2-95eb-aa7ba8a3bd0e'],
['facebook-domain-verification=22rm551cu4k0ab0bxsw536tlds4h95'],
['globalsign-smime-dv=CDYX+XFHUw2wml6/Gb8+59BsH31KzUr6c1l2BPvqKX8='] ]
['1.1.1.1']
[
'ns1.google',
'ns2.google',
'ns4.google',
'ns3.google'
]
packagemain
import(
"fmt"
"net"
)
funcmain() {
ns,err:=net.LookupNS("google")
iferr!=nil{
panic(err)
}
fmt.Printf("%s\n",ns)
ips,err:=net.LookupIP("google")
iferr!=nil{
panic(err)
}
fmt.Println(ips)
mx,err:=net.LookupMX("google")
iferr!=nil{
panic(err)
}
fmt.Println(mx)
txt,err:=net.LookupTXT("google")
iferr!=nil{
panic(err)
}
fmt.Println(txt)
r:=&net.Resolver{
PreferGo:true,
Dial:func(ctxcontext.Context,network,addressstring) (net.Conn,error) {
d:=net.Dialer{
Timeout:time.Millisecond*time.Duration(10_000),
}
returnd.DialContext(ctx,"udp","1.1.1.1:53")
},
}
ns,_=r.LookupNS(context.Background(),"google")
fmt.Printf("%s",ns)
}
Output
[%!s(*net.NS=&{ns3.google.}) %!s(*net.NS=&{ns4.google.}) %!s(*net.NS=&{ns1.google.}) %!s(*net.NS=&{ns2.google.})]
[172.217.5.78 2607:f8b0:4007:80d::200e]
[0xc0000ba2e0 0xc0000ba260 0xc0000ba2a0 0xc0000ba280 0xc0000ba300]
[facebook-domain-verification=22rm551cu4k0ab0bxsw536tlds4h95 docusign=05958488-4752-4ef2-95eb-aa7ba8a3bd0e v=spf1 include:_spf.google~all globalsign-smime-dv=CDYX+XFHUw2wml6/Gb8+59BsH31KzUr6c1l2BPvqKX8=]
[%!s(*net.NS=&{ns2.google.}) %!s(*net.NS=&{ns1.google.}) %!s(*net.NS=&{ns3.google.}) %!s(*net.NS=&{ns4.google.})]
constcrypto=require('crypto')
consthash=crypto.createHash('sha256').update(Buffer.from('hello')).digest()
console.log(hash.toString('hex'))
Output
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
packagemain
import(
"crypto/sha256"
"encoding/hex"
"fmt"
)
funcmain() {
hash:=sha256.Sum256([]byte("hello"))
fmt.Println(hex.EncodeToString(hash[:]))
}
Output
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
constkey=process.env['API_KEY']
console.log(key)
Output
$ API_KEY=foobar node examples/env_vars.js
foobar
packagemain
import(
"fmt"
"os"
)
funcmain() {
key:=os.Getenv("API_KEY")
fmt.Println(key)
}
Output
$ API_KEY=foobar go run examples/env_vars.go
foobar
constargs=process.argv.slice(2)
console.log(args)
Output
$ node examples/cli_args.js foo bar qux
['foo','bar','qux']
packagemain
import(
"fmt"
"os"
)
funcmain() {
args:=os.Args[1:]
fmt.Println(args)
}
Output
$ go run examples/cli_args.go foo bar qux
[foo bar qux]
constyargs=require('yargs')
const{foo='default value',qux=false}=yargs.argv
console.log('foo:',foo)
console.log('qux:',qux)
Output
$ node examples/cli_flags.js --foo='bar'--qux=true
foo: bar
qux:true
packagemain
import(
"flag"
"fmt"
)
funcmain() {
varfoostring
flag.StringVar(&foo,"foo","default value","a string var")
varquxbool
flag.BoolVar(&qux,"qux",false,"a bool var")
flag.Parse()
fmt.Println("foo:",foo)
fmt.Println("qux:",qux)
}
Output
$ go run examples/cli_flags.go -foo='bar'-qux=true
foo: bar
qux:true
process.stdout.write('hello world\n')
Output
hello world
packagemain
import(
"fmt"
"os"
)
funcmain() {
fmt.Fprint(os.Stdout,"hello world\n")
}
Output
hello world
process.stderr.write('hello error\n')
Output
hello error
packagemain
import(
"fmt"
"os"
)
funcmain() {
fmt.Fprint(os.Stderr,"hello error\n")
}
Output
hello error
conststdin=process.openStdin()
process.stdout.write('Enter name: ')
stdin.addListener('data',text=>{
constname=text.toString().trim()
console.log('Your name is: '+name)
stdin.pause()
})
Output
Enter name: bob
Your name is: bob
packagemain
import(
"bufio"
"fmt"
"os"
"strings"
)
funcmain() {
reader:=bufio.NewReader(os.Stdin)
fmt.Print("Enter name:")
text,err:=reader.ReadString('\n')
iferr!=nil{
panic(err)
}
name:=strings.TrimSpace(text)
fmt.Printf("Your name is: %s\n",name)
}
Output
Enter name: bob
Your name is: bob
#initializing metadata and dependencies file (package.json)
$ npm init
#installing a module
$ npm install moment --save
#updating a module
$ npm install moment@latest --save
#removing a module
$ npm uninstall moment --save
#pruning modules (removing unused modules)
$ npm prune
#publishing a module
$ npm publish
// importing a module
constmoment=require('moment')
constnow=moment().unix()
console.log(now)
Output
1546595748
// exporting a module
module.exports={
greet(name){
console.log(`hello${name}`)
}
}
// importing exported module
constgreeter=require('./greeter')
greeter.greet('bob')
Output
hello bob
Setup
#enable Go modules support
GO111MODULE=on
#initializing dependencies file (go.mod)
$ go mod init
#installing a module
$ go get github /go-shadow/moment
#updating a module
$ go get -u github /go-shadow/moment
#removing a module
$ rm -rf$GOPATH/pkg/mod/github /go-shadow/moment@v<tag>-<checksum>/
#pruning modules (removing unused modules from dependencies file)
$ go mod tidy
#download modules being used to local vendor directory (equivalent of downloading node_modules locally)
$ go mod vendor
#publishing a module:
#Note: Go doesn't have an index of repositories like NPM.
#Go modules are hosted as public git repositories.
#To publish, simply push to the repository and tag releases.
packagemain
import(
"fmt"
// importing a module
"github /go-shadow/moment"
)
funcmain() {
now:=moment.New().Now().Unix()
fmt.Println(now)
}
Output
1546595748
packagegreeter
import(
"fmt"
)
// exporting a module (use a capitalized name to export function)
funcGreet(namestring) {
fmt.Printf("hello %s",name)
}
packagemain
import(
// importing exported module
greeter"github /miguelmota/golang-for-nodejs-developers/examples/greeter_go"
)
funcmain() {
greeter.Greet("bob")
}
Output
hello bob
functionfoo(){
thrownewError('failed')
}
try{
foo()
}catch(err){
console.trace(err)
}
Output
Trace: Error: failed
at foo (/Users/bob/examples/stack_trace.js:2:9)
at Object.<anonymous>(/Users/bob/examples/stack_trace.js:6:3)
at Module._compile (internal/modules/cjs/loader.js:688:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)
at Module.load (internal/modules/cjs/loader.js:598:32)
at tryModuleLoad (internal/modules/cjs/loader.js:537:12)
at Function.Module._load (internal/modules/cjs/loader.js:529:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:741:12)
at startup (internal/bootstrap/node.js:285:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:739:3)
at Object.<anonymous>(/Users/bob/examples/stack_trace.js:8:11)
at Module._compile (internal/modules/cjs/loader.js:688:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)
at Module.load (internal/modules/cjs/loader.js:598:32)
at tryModuleLoad (internal/modules/cjs/loader.js:537:12)
at Function.Module._load (internal/modules/cjs/loader.js:529:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:741:12)
at startup (internal/bootstrap/node.js:285:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:739:3)
packagemain
import(
"errors"
"fmt"
"runtime/debug"
)
funcfoo() {
panic(errors.New("failed"))
}
funcmain() {
deferfunc() {
ifr:=recover();r!=nil{
fmt.Println(string(debug.Stack()))
}
}()
foo()
}
Output
goroutine 1 [running]:
runtime/debug.Stack(0xc000090eb8, 0x10a8400, 0xc00007e1c0)
/Users/mota/.gvm/gos/go1.11/src/runtime/debug/stack.go:24 +0xa7
main.main.func1()
/Users/bob/examples/stack_trace.go:16 +0x46
panic(0x10a8400, 0xc00007e1c0)
/Users/mota/.gvm/gos/go1.11/src/runtime/panic.go:513 +0x1b9
main.foo(...)
/Users/bob/examples/stack_trace.go:10
main.main()
/Users/bob/examples/stack_trace.go:20 +0xa2
Example of creating a table, inserting rows, and reading rows from a sqlite3 database
constsqlite3=require('sqlite3').verbose()
constdb=newsqlite3.Database('./sqlite3.db')
db.serialize(()=>{
db.run('CREATE TABLE persons (name TEXT)')
conststmt=db.prepare('INSERT INTO persons VALUES (?)')
constnames=['alice','bob','charlie']
for(leti=0;i<names.length;i++){
stmt.run(names[i])
}
stmt.finalize()
db.each('SELECT rowid AS id, name FROM persons',(err,row)=>{
if(err){
console.error(err)
return
}
console.log(row.id,row.name)
})
})
db.close()
Output
1'alice'
2'bob'
3'charlie'
packagemain
import(
"database/sql"
"fmt"
_"github /mattn/go-sqlite3"
)
funcmain() {
db,err:=sql.Open("sqlite3","./sqlite3.db")
iferr!=nil{
panic(err)
}
deferdb.Close()
_,err=db.Exec("CREATE TABLE persons (name TEXT)")
iferr!=nil{
panic(err)
}
tx,err:=db.Begin()
iferr!=nil{
panic(err)
}
stmt,err:=tx.Prepare("INSERT INTO persons VALUES (?)")
iferr!=nil{
panic(err)
}
deferstmt.Close()
names:=[]string{"alice","bob","charlie"}
for_,name:=rangenames{
_,err:=stmt.Exec(name)
iferr!=nil{
panic(err)
}
}
tx.Commit()
rows,err:=db.Query("SELECT rowid AS id, name FROM persons")
iferr!=nil{
panic(err)
}
deferrows.Close()
forrows.Next() {
varidint
varnamestring
err=rows.Scan(&id,&name)
iferr!=nil{
panic(err)
}
fmt.Println(id,name)
}
err=rows.Err()
iferr!=nil{
panic(err)
}
}
Output
1 alice
2 bob
3 charlie
consttest=require('tape')
test(t=>{
consttt=[
{a:1,b:1,ret:2},
{a:2,b:3,ret:5},
{a:5,b:5,ret:10}
]
t.plan(tt.length)
tt.forEach(tt=>{
t.equal(sum(tt.a,tt.b),tt.ret)
})
})
functionsum(a,b){
returna+b
}
Output
$ node examples/example_test.js
TAP version 13
#(anonymous)
ok 1 should be equal
ok 2 should be equal
ok 3 should be equal
1..3
#tests 3
#pass 3
#ok
packageexample
import(
"fmt"
"testing"
)
funcTestSum(t*testing.T) {
for_,tt:=range[]struct{
aint
bint
retint
}{
{1,1,2},
{2,3,5},
{5,5,10},
} {
t.Run(fmt.Sprintf("(%v + %v)",tt.a,tt.b),func(t*testing.T) {
ret:=sum(tt.a,tt.b)
ifret!=tt.ret{
t.Errorf("want %v, got %v",tt.ret,ret)
}
})
}
}
funcsum(a,bint)int{
returna+b
}
Output
$ gotest-v examples/example_test.go
=== RUN TestSum
=== RUN TestSum/(1_+_1)
=== RUN TestSum/(2_+_3)
=== RUN TestSum/(5_+_5)
--- PASS: TestSum (0.00s)
--- PASS: TestSum/(1_+_1) (0.00s)
--- PASS: TestSum/(2_+_3) (0.00s)
--- PASS: TestSum/(5_+_5) (0.00s)
PASS
ok command-line-arguments 0.008s
constBenchmark=require('benchmark')
constsuite=newBenchmark.Suite
suite.add('fib#recursion',()=>{
fibRec(10)
})
.add('fib#loop',()=>{
fibLoop(10)
})
.on('complete',()=>{
console.log(suite[0].toString())
console.log(suite[1].toString())
})
.run({
async:true
})
functionfibRec(n){
if(n<=1){
returnn
}
returnfibRec(n-1)+fibRec(n-2)
}
functionfibLoop(n){
letf=[0,1]
for(leti=2;i<=n;i++){
f[i]=f[i-1]+f[i-2]
}
returnf[n]
}
Output
$ node examples/benchmark_test.js
fib#recursion x 1,343,074 ops/sec ±1.26% (84 runs sampled)
fib#loop x 20,104,517 ops/sec ±3.78% (78 runs sampled)
packageexample
import(
"testing"
)
funcBenchmarkFibRec(b*testing.B) {
forn:=0;n<b.N;n++{
fibRec(10)
}
}
funcBenchmarkFibLoop(b*testing.B) {
forn:=0;n<b.N;n++{
fibLoop(10)
}
}
funcfibRec(nint)int{
ifn<=1{
returnn
}
returnfibRec(n-1)+fibRec(n-2)
}
funcfibLoop(nint)int{
f:=make([]int,n+1,n+2)
ifn<2{
f=f[0:2]
}
f[0]=0
f[1]=1
fori:=2;i<=n;i++{
f[i]=f[i-1]+f[i-2]
}
returnf[n]
}
Output
$ gotest-v -bench=. -benchmem examples/benchmark_test.go
goos: darwin
goarch: amd64
BenchmarkFibRec-8 5000000 340 ns/op 0 B/op 0 allocs/op
BenchmarkFibLoop-8 30000000 46.5 ns/op 96 B/op 1 allocs/op
PASS
ok command-line-arguments 3.502s
/**
* Creates a new Person.
* @class
* @example
* const person = new Person('bob')
*/
classPerson{
/**
* Create a person.
* @param {string} [name] - The person's name.
*/
constructor(name){
this.name=name
}
/**
* Get the person's name.
* @return {string} The person's name
* @example
* person.getName()
*/
getName(){
returnthis.name
}
/**
* Set the person's name.
* @param {string} name - The person's name.
* @example
* person.setName('bob')
*/
setName(name){
this.name=name
}
}
person.go
packageperson
import"fmt"
// Person is the structure of a person
typePersonstruct{
namestring
}
// NewPerson creates a new person. Takes in a name argument.
funcNewPerson(namestring)*Person{
return&Person{
name:name,
}
}
// GetName returns the person's name
func(p*Person)GetName()string{
returnp.name
}
// SetName sets the person's name
func(p*Person)SetName(namestring)string{
returnp.name
}
person_test.go
// Example of creating a new Person.
funcExampleNewPerson() {
person:=NewPerson("bob")
_=person
}
// Example of getting person's name.
funcExamplePerson_GetName() {
person:=NewPerson("bob")
fmt.Println(person.GetName())
// Output: bob
}
// Example of setting person's name.
funcExamplePerson_SetName() {
person:=NewPerson("alice")
person.SetName("bob")
}
Pull requests are welcome!
Please submit a pull request for new interesting additions or for general content fixes.
If updating code, update both the README and the code in theexamplesfolder.
Released under theMITlicense.