You are on page 1of 78


Installs Go and a text editor.


• •

Windows OSX (32 bit, 64 bit)

The Book
An Introduction to Programming in Go. Cop ri!"t # 2$12 b Caleb %oxse IS&'( )*+,14*+3--+23 ."is boo/ is a0ailable 1or p2r3"ase at 45a6on.3o5 in 7indle or 8aperba3/. It is a0ailable 1or 1ree online below or in 8%9 1or5. :2estions, 3o55ents, 3orre3tions or 3on3erns 3an be sent to Caleb %oxse .

Table of Contents
1. Gettin! Started 1. 9iles and 9olders 2. ."e .er5inal 3. .ext ;ditors 4. Go .ools 2. <o2r 9irst 8ro!ra5 1. =ow to >ead a Go 8ro!ra5 3. . pes 1. '25bers 2. Strin!s 3. &ooleans 4. ?ariables 1. =ow to 'a5e a ?ariable 2. S3ope 3. Constants 4. %e1inin! @2ltiple ?ariables -. 4n ;xa5ple 8ro!ra5 -. Control Str23t2res 1. 9or 2. I1 3. Swit3" 6. 4rra s, Sli3es and @aps 1. 4rra s 2. Sli3es 3. @aps *. 92n3tions 1. <o2r Se3ond 92n3tion 2. >et2rnin! @2ltiple ?al2es 3. ?ariadi3 92n3tions 4. Clos2re -. >e32rsion 6. %e1er, 8ani3 A >e3o0er +. 8ointers 2

1. ."e B and A operators 2. new ). Str23ts and Inter1a3es 1. Str23ts 2. @et"ods 3. Inter1a3es 1$. Con32rren3 1. Goro2tines 2. C"annels 11. 8a3/a!es 1. Creatin! 8a3/a!es 2. %o325entation 12. .estin! 13. ."e Core 8a3/a!es 1. Strin!s 2. Inp2t C O2tp2t 3. 9iles A 9olders 4. ;rrors -. Containers A Sort 6. =as"es A Cr pto!rap" *. Ser0ers +. 8arsin! Co55and Dine 4r!25ents ). S n3"roni6ation 8ri5iti0es 14. 'ext Steps 1. St2d t"e @asters 2. @a/e So5et"in! 3. .ea5 Ep # 2$12 Caleb %oxse . Co0er 4rt( # 2$12 4bi!ail %oxse 4nderson. 4ll >i!"ts >eser0ed. 8ortions o1 t"is pa!e 5a 3ontain 5odi1i3ations based on wor/ 3reated and s"ared b Goo!le and 2sed a33ordin! to ter5s des3ribed in t"e Creati0e Co55ons 3.$ 4ttrib2tion Di3ense.


. . On OSX (and 5ost ot"er operatin! s ste5s) 1ile and 1older pat"s are represented wit" t"e / (1orward slas") 3"ara3ter."e pro3ess we 2se to write so1tware 2sin! Go (and 5ost pro!ra55in! lan!2a!es) is 1airl strai!"t1orward( • • • • • Gat"er reF2ire5ents 9ind a sol2tion Write so2r3e 3ode to i5ple5ent t"e sol2tion Co5pile t"e so2r3e 3ode into an exe32table >2n and test t"e pro!ra5 to 5a/e s2re it wor/s . example. Go is an ideal lan!2a!e to learn as o2r 1irst pro!ra55in! lan!2a!e. On Windows 1ile and 1older pat"s (lo3ations) are represented wit" t"e \ (ba3/slas") 3"ara3ter."is pro3ess is iterati0e (5eanin! its done 5an ti5es) and t"e steps 2s2all o0erlap. Di/e on Windows example. @odern operatin! s ste5s (li/e Windows or @a3 OSX) 3ontain 5illions o1 1iles w"i3" store a lar!e 0ariet o1 di11erent t pes o1 in1or5ation G e0er t"in! 1ro5 text do325ents to exe32table pro!ra5s to 52lti5edia 1iles. 9olders (also 3alled dire3tories) are 2sed to !ro2p 1iles to!et"er. 1or exa5ple( /Users/john/example. it is 4 . Files and Folders 4 1ile is a 3olle3tion o1 data stored as a 2nit wit" a na5e. its rob2st well. 1or exa5ple( C:\Users\john\example.. &e3a2se o1 its wide a0ailabilit on a 0ariet o1 plat1or5s.txt "as t"e extension txt w"i3" is 2sed to represent text2al data."e 3an also 3ontain ot"er 1olders. and its 1o32s on !ood so1tware en!ineerin! prin3iples. pi3all t"e 1ileHs t pe is si!ni1ied b t"e 1ileHs extension G t"e part o1 t"e 1ile na5e t"at 3o5es a1ter t"e last . &2t be1ore we write o2r 1irst pro!ra5 in Go t"ere are a 1ew prereF2isite 3on3epts we need to 2nderstand.txt is t"e 1ile na5e.Getting Started Co5p2ter pro!ra55in! is t"e art. 4ll 1iles are stored in t"e sa5e wa on a 3o5p2ter( t"e all "a0e a na5e.txt. . ."is boo/ will tea3" o2 "ow to write 3o5p2ter pro!ra5s 2sin! a pro!ra55in! lan!2a!e desi!ned b Goo!le na5ed Go. 9or exa5ple a 1ile wit" t"e na5e hello. do325ented 3o55on librar .txt. a de1inite si6e (5eas2red in b tes) and an asso3iated t pe. Go is a !eneral p2rpose pro!ra55in! lan!2a!e wit" ad0an3ed 1eat2res and a 3lean s ntax. it is 3ontained in t"e 1older john.txt is t"e 1ile na5e. 3ra1t and s3ien3e o1 writin! pro!ra5s w"i3" de1ine "ow 3o5p2ters operate. w"i3" is itsel1 3ontained in t"e 1older Users w"i3" is stored on dri0e C (w"i3" represents t"e pri5ar p" si3al "ard dri0e in Windows).

xplorer (a33essible b do2ble.3li3/in! I@ Co5p2terJ or t pin! winKe)( OSX On OSX 1iles and 1olders 3an be browsed 2sin! 9inder (a33essible b 3li3/in! t"e 9inder i3on G t"e 1a3e i3on in t"e lower le1t bar)( - .3ontained in t"e 1older john. OSX does not spe3i1 a dri0e letter w"ere t"e 1ile is stored. w"i3" is in t"e 1older Users. Enli/e Windows. Windows On Windows 1iles and 1olders 3an be browsed 2sin! Windows .

It wasnHt alwa s t"is wa . <o2 s"o2ld see a bla3/ window appear t"at loo/s li/e t"is( 6 . Windows In Windows t"e ter5inal (also /nown as t"e 3o55and line) 3an be bro2!"t 2p b t pin! t"e windows /e K r ("old down t"e windows /e t"en press r). .The Terminal @ost o1 t"e intera3tions we "a0e wit" 3o5p2ters toda are t"ro2!" sop"isti3ated !rap"i3al 2ser inter1a3es (GEIs). t pin! cmd. and so be1ore we write a pro!ra5 in Go we need to "a0e a r2di5entar 2nderstandin! o1 "ow a ter5inal wor/s. 5i3e and to23"s3reens to intera3t wit" 0is2al b2ttons or ot"er t pes o1 3ontrols t"at are displa ed on a s3reen."e Go pro!ra55in! lan!2a!e is no di11erent. t"e tr2t" is t"at t"e ter5inal is still t"e 12nda5ental 2ser inter1a3e 2sed b 5ost pro!ra55in! lan!2a!es on 5ost 3o5p2ters. &e1ore t"e GEI we "ad t"e ter5inal G a si5pler text2al inter1a3e to t"e 3o5p2ter w"ere rat"er t"an 5anip2latin! b2ttons on a s3reen we iss2ed 3o55ands and re3ei0ed replies.exe and "ittin! enter. 4nd alt"o2!" it 5i!"t appear t"at 5ost o1 t"e 3o5p2tin! world "as le1t be"ind t"e ter5inal as a reli3 o1 t"e past. We "ad a 3on0ersation wit" t"e 3o5p2ter. We 2se /e boards.

.. <o2 s"o2ld see a window li/e t"is( * . b2t t"is s"o2ld be eno2!" to !et o2 started.. . doesnHt do an t"in!. <o2 3an see its 3ontents b enterin! cd %es&top and t"en enterin! dir. so cd .r enterin! t"e 3o55and dir. (In 5 3ase t"is is C:\Users\caleb) <o2 iss2e 3o55ands b t pin! t"e5 in and "ittin! enter..& de1a2lt t"e 3o55and line starts in o2r "o5e dire3tor .o !o ba3/ to o2r "o5e dire3tor o2 3an 2se t"e spe3ial dire3tor na5e . 9or exa5ple o2 probabl "a0e a 1older 3alled %es&top. 4 sin!le period represents t"e 32rrent 1older (/nown as t"e wor/in! 1older). Volume Serial Number is B !"#!$ " 9ollowed b a list o1 t"e 1iles and 1olders 3ontained in o2r "o5e dire3tor . <o2 s"o2ld see so5et"in! li/e t"is( C:\Users\caleb>dir Volume in drive C has no label. <o2 3an 3"an!e dire3tories b 2sin! t"e 3o55and cd."ere are a lot 5ore 3o55ands o2 3an 2se. w"i3" lists t"e 3ontents o1 a dire3tor . . (two periods next to ea3" ot"er)( cd .er5inal. OSX In OSX t"e ter5inal 3an be rea3"ed b !oin! to 9inder L 4ppli3ations L Etilities L .

b2t t"is s"o2ld be eno2!" to !et o2 started. <o2 3an 3"an!e dire3tories 2sin! t"e cd 3o55and. .!olan!. <o2 3an see its 3ontents b enterin! cd %es&top and t"en enterin! ls. <o2 s"o2ld see so5et"in! li/e t"is( caleb#min:' caleb( ls %es&top %o)nloads %ocuments . . M) b2t 2nli/e s23" pro!ra5s t"e donHt do an 1or5attin!.ibrar*ovies *usic +ictures +ublic . 9or exa5ple o2 probabl "a0e a 1older 3alled %es&top.& de1a2lt t"e ter5inal starts in o2r "o5e dire3tor ."ese are t"e 1iles and 1olders 3ontained in o2r "o5e dire3tor (in t"is 3ase t"ere are no 1iles).r enterin! t"e 3o55and ls.. set2p en0iron5ental 0ariables and install a text editor. so cd . (In 5 3ase t"is is /Users/caleb) <o2 iss2e 3o55ands b t pin! t"e5 in and "ittin! enter. doesnHt do an t"in!. &ot" OSX and Windows 3o5e wit" text editors b2t t"e are "i!"l li5ited and I re3o55end installin! a better one.ext editors are si5ilar to word pro3essin! pro!ra5s (@i3roso1t Word. w"i3" lists t"e 3ontents o1 a dire3tor . ."is installer will install t"e Go tool s2ite. .."ere are a lot 5ore 3o55ands o2 3an 2se. 4 sin!le period represents t"e 32rrent 1older (/nown as t"e wor/in! 1older). Open O11i3e. (two periods next to ea3" ot"er)( cd . Text Editors . ('o bold.. . M) instead t"e operate onl on plain text.o 5a/e t"e installation o1 t"is so1tware easier an installer is a0ailable at t"e boo/Hs website( "ttp(CCwww. . + .3o5C."e pri5ar tool pro!ra55ers 2se to write so1tware is a text editor.o !o ba3/ to o2r "o5e dire3tor o2 3an 2se t"e spe3ial dire3tor na5e .

"e 5en2s list t"e s"ort32ts to t"eir ri!"t. 4s o2 wor/ in a text editor it is 2se12l to learn /e board s"ort32ts. <o2 3an open 1iles b !oin! to 9ile L Open and browsin! to o2r desired 1ile. 4t t"e botto5 o1 t"e window is a stat2s bar w"i3" displa s in1or5ation abo2t t"e 1ile and o2r 32rrent lo3ation in it (ri!"t now it sa s t"at we are on line 1. and we are 2sin! windows. 9iles 3an be sa0ed b !oin! to 9ile L Sa0e or 9ile L Sa0e 4s. 3ol25n 1. <o2 3an open it b !oin! to Start L 4ll 8ro!ra5s L Go L S3ite. =ere are a 1ew o1 t"e 5ost 3o55on( • • Ctrl K S G sa0e t"e 32rrent 1ile Ctrl K X G 32t t"e 32rrentl sele3ted text (re5o0e it and p2t it in o2r 3lipboard so it 3an be pasted later) Ctrl K C G 3op t"e 32rrentl sele3ted text Ctrl K ? G paste t"e text 32rrentl in t"e 3lipboard Ese t"e arrow /e s to na0i!ate."e text editor 3ontains a lar!e w"ite text area w"ere text 3an be entered. <o2 s"o2ld see so5et"in! li/e t"is( .o t"e le1t o1 t"is text area o2 3an see t"e line n25bers. text is bein! inserted nor5all . =o5e to !o to t"e be!innin! o1 t"e line and .nd to !o to t"e end o1 t"e line • • • ) .Windows 9or windows t"e installer will install t"e S3ite text editor. . .st le newlines).

ext Wran!ler 3ontains a lar!e w"ite area w"ere text is entered. 9iles 3an be opened b !oin! to 9ile L Open. 9iles 3an be sa0ed b !oin! to 9ile L Sa0e or 9ile L Sa0e 4s. =ere are so5e 2se12l /e board s"ort32ts( (Co55and is t"e ⌘ /e ) • • Co55and K S G sa0e t"e 32rrent 1ile Co55and K X G 32t t"e 32rrentl sele3ted text (re5o0e it and p2t it in o2r 3lipboard so it 3an be pasted later) Co55and K C G 3op t"e 32rrentl sele3ted text Co55and K ? G paste t"e text 32rrentl in t"e 3lipboard Ese t"e arrow /e s to na0i!ate 1$ • • • .ext Wran!ler text editor( Di/e S3ite on Windows .nd) to sele3t text wit"o2t 2sin! t"e 5o2se Ctrl K 9 G brin!s 2p a 1ind in 1ile dialo! t"at o2 3an 2se to sear3" t"e 3ontents o1 a 1ile • OSX 9or OSX t"e installer installs t"e .• =old down s"i1t w"ile 2sin! t"e arrow /e s (or =o5e and .

/. (@ore in1or5ation 3an be 1o2nd at "ttp(CCwww. . Open 2p a ter5inal and t pe t"e 1ollowin!( .o$.o help We will see "ow t"e are 2sed in s2bseF2ent 3"apters. we need t"e Go 3o5piler."e installer will set2p Go 1or o2 a2to5ati3all . . I1 o2 !et an error abo2t t"e 3o55and not bein! re3o!ni6ed tr restartin! o2r 3o5p2ter.or!) DetHs 5a/e s2re e0er t"in! is wor/in!. w"i3" 5eans so2r3e 3ode (t"e 3ode o2 write) is translated into a lan!2a!e t"at o2r 3o5p2ter 3an 2nderstand. .• Co55and K 9 G brin!s 2p a 1ind in 1ile dialo! t"at o2 3an 2se to sear3" t"e 3ontents o1 a 1ile Go Tools Go is a 3o5piled pro!ra55in! lan!2a!e.o version .!olan!.o version <o2 s"o2ld see t"e 1ollowin!( .3o55ands. <o2r 0ersion n25ber 5a be sli!"tl di11erent. We will be 2sin! 0ersion 1 o1 t"e lan!2a!e."e Go tool s2ite is 5ade 2p o1 se0eral di11erent 3o55ands and s2b."ere1ore be1ore we 3an write a Go pro!ra5. 11 . 4 list o1 t"ose 3o55ands is a0ailable b t pin!( .

"ere are two t pes o1 Go pro!ra5s( exe32tables and libraries. le1t to ri!"t.o run main.olan.olan.olan. . Di/e 5ost 3o5pilers.o <o2 s"o2ld see 0ello 1orld displa ed in o2r ter5inal."e installer o2 2sed in 3"apter 1 3reated a 1older in o2r "o5e dire3tor na5ed 2o."e 1irst line sa s t"is( pac&a. .Your First Program . I1 o2 didnHt see 0ello 1orld displa ed o2 5a "a0e 5ade a 5ista/e w"en t pin! in t"e pro!ra5. 8a3/a!es are GoHs wa o1 or!ani6in! and re2sin! 3ode.. Create a 1older na5ed '/2o/src/.xe32table appli3ations are t"e /inds o1 pro!ra5s t"at we 3an r2n dire3tl 1ro5 t"e ter5inal. DetHs write one 2sin! Go. .#boo&/chapter Esin! o2r text editor t pe in t"e 1ollowin!( pac&a.+rintln530ello 1orld36 8 @a/e s2re o2r 1ile is identi3al to w"at is s"own "ere and sa0e it as main."e Go 3o5piler will !i0e o2 "ints abo2t w"ere t"e 5ista/e lies. .#boo& m&dir 2o/src/. (li/e a boo/) . 3o5piles t"e5 into an exe32table sa0ed in a te5porar dire3tor and t"en r2ns t"e pro!ra5. 9irst 3reate a new 1older w"ere we 3an store o2r pro!ra5.o in t"e 1older we N2st 3reated. (in Windows t"e end 12 .#boo&/chapter ."e .olan. .e main .0er Go pro!ra5 52st start wit" a pa3/a!e de3laration.e main import 34mt3 // this is a comment 4unc main56 7 4mt. . Go pro!ra5s are read top to botto5.raditionall t"e 1irst pro!ra5 o2 write in an pro!ra55in! lan!2a!e is 3alled a I=ello WorldJ pro!ra5 G a pro!ra5 t"at si5pl o2tp2ts 0ello 1orld to o2r ter5inal. Open 2p a new ter5inal and t pe in t"e 1ollowin!( cd 2o/src/. (W"ere ' 5eans o2r "o5e dire3tor ) 9ro5 t"e ter5inal o2 3an do t"is b enterin! t"e 1ollowin! 3o55ands( m&dir 2o/src/..#boo&/chapter . How to Read a Go Program DetHs loo/ at t"is pro!ra5 in 5ore detail. t"e Go 3o5piler is extre5el pedanti3 and "as no toleran3e 1or 5ista/es.o run 3o55and ta/es t"e s2bseF2ent 1iles (separated b spa3es)."is is /nown as a Ipa3/a!e de3larationJ.

M) o1 a de1inite len!t"."e 3 3"ara3ter itsel1 is not part o1 t"e strin!) ."e import /e word is "ow we in3l2de 3ode 1ro5 ot"er pa3/a!es to 2se wit" o2r pro!ra5. . . (. We will explore libraries in 5ore detail later. n25bers."e 4mt pa3/a!e (s"ort"and 1or 1or5at) i5ple5ents 1or5attin! 1or inp2t and o2tp2t. Go s2pports two di11erent st les o1 3o55ents( // 3o55ents in w"i3" all t"e text between t"e // and t"e end o1 t"e line is part o1 t"e 3o55ent and /9 9/ 3o55ents w"ere e0er t"in! between t"e 9s is part o1 t"e 3o55ent."e "a0e inp2ts. doesnHt ret2rn an t"in! and "as onl one state5ent. 1or now N2st 5a/e s2re to in3l2de t"is line in an pro!ra5 o2 write. ."en we see t"is( import 34mt3 ."is 12n3tion "as no para5eters. spa3es and tabs are /nown as w"itespa3e (be3a2se o2 3anHt see t"e5). a list o1 6ero or 5ore Ipara5etersJ s2rro2nded b parent"eses. . an optional ret2rn t pe and a Ibod J w"i3" is s2rro2nded b 32rl bra3es. Strin!s are des3ribed in 5ore detail in t"e next 3"apter. (4nd 5a in3l2de 52ltiple lines) 41ter t"is o2 see a 12n3tion de3laration( 4unc main56 7 4mt. Gi0en w"at we N2st learned abo2t pa3/a!es w"at do o2 t"in/ t"e 4mt pa3/a!eHs 1iles wo2ld 3ontain at t"e top o1 t"e5O 'oti3e t"at 4mt abo0e is s2rro2nded b do2ble F2otes."e 1inal pie3e o1 o2r pro!ra5 is t"is line( 13 . Co55ents are i!nored b t"e Go 3o5piler and are t"ere 1or o2r own sa/e (or w"oe0er pi3/s 2p t"e so2r3e 3ode 1or o2r pro!ra5). s 5bols. Co5p2ters represent newlines wit" a spe3ial 3"ara3ter (or se0eral 3"ara3ters). (<o2 3o2ld re5o0e t"is line and t"e pro!ra5 wo2ld be"a0e in exa3tl t"e sa5e wa ) . b2t 1or now t"e i5portant t"in! to /eep in 5ind is t"at an openin! 3 3"ara3ter 52st e0ent2all be 1ollowed b anot"er 3 3"ara3ter and an t"in! in between t"e two is in3l2ded in t"e strin!. 4ll 12n3tions start wit" t"e /e word 4unc 1ollowed b t"e na5e o1 t"e 12n3tion (main in t"is 3ase). .wit" . . In Go strin!s represent a seF2en3e o1 3"ara3ters (letters."e line t"at starts wit" // is /nown as a 3o55ent."e 2se o1 do2ble F2otes li/e t"is is /nown as a Istrin! literalJ w"i3" is a t pe o1 IexpressionJ. Go 5ostl doesnHt 3are abo2t w"itespa3e."e na5e main is spe3ial be3a2se itHs t"e 12n3tion t"at !ets 3alled w"en o2 exe32te t"e pro!ra5.+rintln530ello 1orld36 8 92n3tions are t"e b2ildin! blo3/s o1 a Go pro!ra5. o2tp2ts and a series o1 steps 3alled state5ents w"i3" are exe32ted in order. . we 2se it to 5a/e pro!ra5s easier to read.exe) Dibraries are 3olle3tions o1 3ode t"at we pa3/a!e to!et"er so t"at we 3an 2se t"e5 in ot"er pro!ra5s. 'ewlines."e next line is a blan/ line.

Spaces are al)a-s added bet)een operands and a ne)line is appended. . t"is do325entation is tellin! o2 t"at t"e +rintln 12n3tion will send w"ate0er o2 !i0e to it to standard o2tp2t G a na5e 1or t"e o2tp2t o1 t"e ter5inal o2 are wor/in! in. <o2 3an 1ind o2t 5ore abo2t it b t pin! t"e 1ollowin! in o2r ter5inal( . ."at 12n3tion ta/es no ar!25ents. 9irst we a33ess anot"er 12n3tion inside o1 t"e 4mt pa3/a!e 3alled +rintln (t"atHs t"e 4mt. In t"e next 3"apter we will explore "ow Go stores and represents t"in!s li/e 0ello 1orld b learnin! abo2t t pes. Go is a 0er well do325ented pro!ra55in! lan!2a!e b2t t"is do325entation 3an be di11i32lt to 2nderstand 2nless o2 are alread 1a5iliar wit" pro!ra55in! lan!2a!es."en we 3reate a new strin! t"at 3ontains 0ello 1orld and in0o/e (also /nown as 3all or exe32te) t"at 12n3tion wit" t"e strin! as t"e 1irst and onl ar!25ent.4mt."is 12n3tion is w"at 3a2ses 0ello 1orld to be displa ed."e +rintln 12n3tion does t"e real wor/ in t"is pro!ra5. 'e0ert"eless t"e .odoc 3o55and is extre5el 2se12l and a !ood pla3e to start w"ene0er o2 "a0e a F2estion. the de4ault 4ormats 4or its operands and )rites to standard output. W"at wo2ld t"e 1iles in t"e 4mt pa3/a!e be!in wit"O 14 .e main."is state5ent is 5ade o1 t"ree 3o5ponents. w"i3" re1eren3es t"e 4mt librar and 3ontains one 12n3tion 3alled main. So5eti5es its "elp12l to deliberatel read o2r pro!ra5 o2t lo2d. One readin! o1 t"e pro!ra5 we N2st wrote 5i!"t !o li/e t"is( Create a new exe32table pro!ra5.odoc 4mt +rintln 45on! ot"er t"in!s o2 s"o2ld see t"is( +rintln 4ormats usin. .+rintln530ello 1orld36 . &a3/ to t"e 12n3tion at "and. . 4t t"is point weH0e alread seen a lot o1 new ter5inolo! and o2 5a be a bit o0erw"el5ed. doesnHt ret2rn an t"in! and does t"e 1ollowin!( 433ess t"e +rintln 12n3tion 3ontained inside o1 t"e 4mt pa3/a!e and in0o/e it 2sin! one ar!25ent G t"e strin! 0ello 1orld.+rintln pie3e. Problems • • • W"at is w"itespa3eO W"at is a 3o55entO W"at are t"e two wa s o1 writin! a 3o55entO O2r pro!ra5 be!an wit" pac&a. :t returns the number o4 b-tes )ritten and an)rite error encountered. +rintln 5eans 8rint Dine).

name is 1ollowed b o2r na5e. x is a strin!. $. t"ere1ore x "as a len!t". Go 3o5es wit" se0eral b2ilt. b. Sin3e t pes 3an be a di11i32lt 3on3ept to !rasp we will loo/ at t"e5 1ro5 a 3o2ple di11erent perspe3ti0es be1ore we see "ow t"e are i5ple5ented in Go.• We 2sed t"e +rintln 12n3tion de1ined in t"e 4mt pa3/a!e.J In t"is wa sets are si5ilar to t pes in pro!ra55in! lan!2a!es sin3e all t"e 0al2es o1 a parti32lar t pe s"are 3ertain properties.1$ de3i5al s ste5 we 2se to represent n25bers. des3ribe t"e operations t"at 3an be done on t"e5 and de1ine t"e wa t"e are stored. 8"ilosop"ers so5eti5es 5a/e a distin3tion between t pes and to/ens.3. Stati3 t pin! 5a see5 325berso5e at 1irst. • Types In t"e last 3"apter we 2sed t"e data t pe strin! to store 0ello 1orld. and 3. 4lt"o2!" o0ersi5plisti3 we 5i!"t reason li/e t"is( 4ll do!s "a0e 4 le!s.xit 12n3tion 1ro5 t"e os pa3/a!e w"at wo2ld we need to doO @odi1 t"e pro!ra5 we wrote so t"at instead o1 printin! 0ello 1orld it prints 0ello< m. Go is a stati3all t ped pro!ra55in! lan!2a!e. &2t t pes "elp 2s reason abo2t w"at o2r pro!ra5 is doin! and 3at3" a wide 0ariet o1 3o55on 5ista/es.2. 3o5p2ters 2se a base. Numbers Go "as se0eral di11erent t pes to represent n25bers. t"ere1ore @ax "as 4 le!s. %ata t pes 3ate!ori6e a set o1 related 0al2es. 9or exa5ple s2ppose o2 "a0e a do! na5ed @ax. Integers Inte!ers G li/e t"eir 5at"e5ati3al 3o2nterpart G are n25bers wit"o2t a de3i5al 3o5ponent. 9or exa5ple( ℝ (t"e set o1 all real n25bers) or ℕ (t"e set o1 all nat2ral n25bers). .point n25bers. 1- .a3" 5e5ber o1 t"ese sets s"ares properties wit" all t"e ot"er 5e5bers o1 t"e set. @ax is t"e to/en (a parti32lar instan3e or 5e5ber) and do! is t"e t pe (t"e !eneral 3on3ept). 1. a K (b K 3) P (a K b) K 3 and a Q (b Q 3) P (a Q b) Q 3. ."is 5eans t"at 0ariables alwa s "a0e a spe3i1i3 t pe and t"at t pe 3annot 3"an!e. . In 5at"e5ati3s we o1ten tal/ abo2t sets. . Generall we split n25bers into two di11erent /inds( inte!ers and 1loatin!. I1 we wanted to 2se t"e . 9or exa5ple all nat2ral n25bers are asso3iati0e( I1or all nat2ral n25bers a. I%o!J or Ido!nessJ des3ribes a set o1 properties t"at all do!s "a0e in 3o55on.2 binar s ste5. @ax is a do!. M) Enli/e t"e base. . ( data t pes w"i3" we will now loo/ at in 5ore detail.1. <o2Hll spend a lar!e a5o2nt o1 o2r ti5e N2st tr in! to 1ix o2r pro!ra5 so t"at it 1inall 3o5piles. pes in pro!ra55in! lan!2a!es wor/ in a si5ilar wa ( 4ll strin!s "a0e a len!t". .

111 and so on. uint? . int=. b2t not exa3tl t"e sa5e. 32 and 64 tell 2s "ow 5an bits ea3" o1 t"e t pes 2se. Generall i1 o2 are wor/in! wit" inte!ers o2 s"o2ld N2st 2se t"e int t pe. On3e weH0e ex"a2sted o2r a0ailable di!its we represent lar!er n25bers b 2sin! 2 (t"en 3. 1$$. (BC and DC) • Go "as two 1loatin! point t pes( 4loat? and 4loat>@ (also o1ten re1erred to as sin!le pre3ision and do2ble pre3ision respe3ti0el ) as well as two additional t pes 1or representin! 3o5plex n25bers (n25bers wit" i5a!inar parts)( complex>@ and complex$ =. M) and t"ere1ore GoHs b-te data t pe is o1ten 2sed in t"e de1inition o1 ot"er t pes.O2r s ste5 is 5ade 2p o1 1$ di11erent di!its. ."eir a3t2al representation on a 3o5p2ter is 1airl 3o5pli3ated and not reall ne3essar in order to /now "ow to 2se t"e5. . 16. 1234$$$$) . Di/e inte!ers 1loatin! point n25bers "a0e a 3ertain si6e (32 bit or 64 bit). uint$>. b2t t"e onl "a0e 2 di!its instead o1 1$. .$$$$1234./ //////////////$= G 4 n25ber extre5el 3lose to w"at we wo2ld expe3t. $$11. 9or exa5ple 3o5p2tin! $. 1$24 /ilob tes P 1 5e!ab te. So 3o2ntin! loo/s li/e t"is( $. . In addition t"ere two alias t pes( b-te w"i3" is t"e sa5e as uint= and rune w"i3" is t"e sa5e as int? . 11. $$1$. ."e onl "a0e roo5 1or a 3ertain n25ber o1 di!its. So 1or now we need onl /eep t"e 1ollowin! in 5ind( • • 9loatin! point n25bers are inexa3t. Co5p2ters do t"e sa5e. Generall we s"o2ld sti3/ wit" 4loat>@ w"en wor/in! wit" 1loatin! point n25bers. O33asionall it is not possible to represent a n25ber."e are 5a3"ine dependent be3a2se t"eir si6e depends on t"e t pe o1 ar3"ite3t2re o2 are 2sin!.0ent2all we r2n o2t o1 spa3e and 5ost 3o5p2ters N2st wrap aro2nd to t"e be!innin!. uint 5eans I2nsi!ned inte!erJ w"ile int 5eans Isi!ned inte!erJ. 1$1.4. & tes are an extre5el 3o55on 2nit o1 5eas2re5ent 2sed on 3o5p2ters (1 b te P + bits. Esin! a lar!er si6ed 1loatin! point n25ber in3reases itHs pre3ision. ("ow 5an di!its it 3an represent) In addition to n25bers t"ere are se0eral ot"er 0al2es w"i3" 3an be represented( Inot a n25berJ (NaN. -. 1$.234. 1. $. $$$1. Ensi!ned inte!ers onl 3ontain positi0e n25bers (or 6ero). uint>@. int$>. 9or exa5ple t"e n25ber a1ter ) is 1$."e ot"er di11eren3e between t"e n25ber s ste5 we 2se and t"e one 3o5p2ters 2se is t"at all o1 t"e inte!er t pes "a0e a de1inite si6e. 1or t"in!s li/e ///) and positi0e and ne!ati0e in1init . (W"i3" 3an res2lt in so5e 0er stran!e be"a0ior) GoHs inte!er t pes are( uint=. int and uintptr. 11$. 4./$ # /.AA res2lts in /. 123. So a 4 bit inte!er 5i!"t loo/ li/e t"is( $$$$. $1$$. 1$24 b tes P 1 /ilob te."ere are also 3 5a3"ine dependent inte!er t pes( uint. Floating Point Numbers 9loatin! point n25bers are n25bers t"at 3ontain a de3i5al 3o5ponent (real n25bers). (1. int? and int>@. 16 . t"e n25ber a1ter )) is 1$$ and so on. M) di!its p2t next to ea3" ot"er. +.

Example DetHs write an exa5ple pro!ra5 2sin! n25bers.o $ B $ E 'oti3e t"at t"is pro!ra5 is 0er si5ilar to t"e pro!ra5 we wrote in 3"apter 2. It 3ontains t"e sa5e pa3/a!e line. DetHs tr t"e sa5e t"in! 2sin! 1loatin! point n25bers( 4mt."is ti5e instead o1 printin! t"e strin! 0ello 1orld we print t"e strin! $ B $ E 1ollowed b t"e res2lt o1 t"e expression $ B $.+rintln53$ B $ E3< $. t"e B operator (w"i3" represents addition) and anot"er n25eri3 literal $. . In addition to addition Go "as se0eral ot"er operators( K . t"e sa5e 12n3tion de3laration and 2ses t"e sa5e +rintln 12n3tion.+rintln53$ B $ E3< $ B $6 8 I1 o2 r2n t"e pro!ra5 and o2 s"o2ld see t"is( ( ."e di11eren3e between t"ese is t"at do2ble F2oted strin!s 3annot 3ontain newlines and t"e allow spe3ial es3ape seF2en3es."is expression is 5ade 2p o1 t"ree parts( t"e n25eri3 literal $ (w"i3" is o1 t pe int)./6 'oti3e t"at we 2se t"e . Go strin!s are 5ade 2p o1 indi0id2al b tes. 9irst 3reate a 1older 3alled chapter? and 5a/e a main. . . 2s2all one 1or ea3" 3"ara3ter. 1* ./ to tell Go t"at t"is is a 1loatin! point n25ber instead o1 an inte!er./ B $... (C"ara3ters 1ro5 ot"er lan!2a!es li/e C"inese are represented b 5ore t"an one b te) Strin! literals 3an be 3reated 2sin! do2ble F2otes 30ello 1orld3 or ba3/ ti3/s F0ello 1orldF. 9or exa5ple \n !ets repla3ed wit" a newline and \t !ets repla3ed wit" a tab 3"ara3ter.o run main. t"e sa5e i5port line. >2nnin! t"is pro!ra5 will !i0e o2 t"e sa5e res2lt as be1ore. B C R addition s2btra3tion 52ltipli3ation di0ision re5ainder trings 4s we saw in 3"apter 2 a strin! is a seF2en3e o1 3"ara3ters wit" a de1inite len!t" 2sed to represent text.e main import 34mt3 4unc main56 7 4mt.o 1ile 3ontainin! t"e 1ollowin!( pac&a.

so t"e strin!Hs len!t" is 11 not 1$ and t"e 3rd line "as 30ello 3 instead o1 30ello3. and 3on3atenatin! two strin!s to!et"er( 30ello 3 B 31orld3.+rintln5true II 4mt.+rintln5Ktrue6 8 true6 4alse6 true6 4alse6 1+ . . G$H !i0es o2 t"e 2nd ele5ent not t"e 1st.+rintln530ello 3 B 31orld36 8 4 1ew t"in!s to noti3e( • • 4 spa3e is also 3onsidered a 3"ara3ter.e main import 34mt3 4unc main56 7 4mt. DetHs 5odi1 t"e pro!ra5 we 3reated earlier to test t"ese o2t( pac&a.+rintln5true JJ 4mt. One wa to t"in/ abo2t indexin! wo2ld be to s"ow it li/e t"is instead( 30ello 1orld3$."ree lo!i3al operators are 2sed wit" boolean 0al2es( AA and SS or T not =ere is an exa5ple pro!ra5 s"owin! "ow t"e 3an be 2sed( 4unc main56 7 4mt. • Con3atenation 2ses t"e sa5e s 5bol as addition. (4ddition is 5eanin!less 1or strin!s) Booleans 4 boolean 0al2e (na5ed a1ter Geor!e &oole) is a spe3ial 1 bit inte!er t pe 2sed to represent tr2e and 1alse (or on and o11). ."e strin! =ello World s2b 1."is is be3a2se t"e 3"ara3ter is represented b a b te (re5e5ber a b te is an inte!er).+rintln5true II 4mt. a33essin! an indi0id2al 3"ara3ter in t"e strin!( 30ello 1orld3G$H. Sin3e bot" sides o1 t"e B are strin!s t"e 3o5piler ass25es o2 5ean 3on3atenation and not addition. 4lso noti3e t"at o2 see $/$ instead o1 e w"en o2 r2n t"is pro!ra5."e se3ond 3"ara3ter o1 t"e strin! =ello WorldJ.+rintln5len530ello 1orld366 4mt. Strin!s are IindexedJ startin! at $ not 1.+rintln530ello 1orld3G$H6 4mt.+rintln5true JJ 4mt.J I."e strin! =ello World at 1J or I.Se0eral 3o55on operations on strin!s in3l2de 1indin! t"e len!t" o1 a strin!( len530ello 1orld36. <o2Hd read t"at as I. ."e Go 3o5piler 1i!2res o2t w"at to do based on t"e t pes o1 t"e ar!25ents.

xpression ?al2e Ttr2e 1alse T1alse tr2e ."ese are t"e si5plest t pes in3l2ded wit" Go and 1or5 t"e 1o2ndation 1ro5 w"i3" all later t pes are b2ilt.xpression ?al2e tr2e AA tr2e tr2e tr2e AA 1alse 1alse 1alse AA tr2e 1alse 1alse AA 1alse 1alse .o true 4alse true true 4alse We 2s2all 2se tr2t" tables to de1ine "ow t"ese operators wor/( .o run main. t"e lar!est 3 di!it n25ber is 111 (*) and t"e lar!est 4 di!it n25ber is 1111 (1-) w"atHs t"e lar!est + di!it n25berO ("int( 1$1.1 P ))) 4lt"o2!" o0erpowered 1or t"e tas/ o2 3an 2se Go as a 3al32lator.xpression ?al2e tr2e SS tr2e tr2e tr2e SS 1alse tr2e 1alse SS tr2e tr2e 1alse SS 1alse 1alse . (Ese t"e 9 operator 1or 52ltipli3ation) W"at is a strin!O =ow do o2 1ind its len!t"O W"atHs t"e 0al2e o1 t"e expression 5true II 4alse6 JJ 54alse II true6 JJ K54alse II 4alse6O • • • 1) .1 P ) and 1$2. Gi0en t"at in binar t"e lar!est 2 di!it n25ber is 11 (3). Problems • • =ow are inte!ers stored on a 3o5p2terO We /now t"at (in base 1$) t"e lar!est 1 di!it n25ber is ) and t"e lar!est 2 di!it n25ber is )).>2nnin! t"is pro!ra5 s"o2ld !i0e o2( ( . Write a pro!ra5 t"at 3o5p2tes ? $? " L @ @" $ and prints it to t"e ter5inal..

b2t itHs better to read it as Ix ta/es t"e strin! =ello WorldJ or Ix is assi!ned t"e strin! =ello WorldJ.o 5a/e tr2l 2se12l pro!ra5s we need to learn two new 3on3epts( 0ariables and 3ontrol 1low state5ents. strin!s. x E 30ello 1orld3 4mt.ariables Ep 2ntil now we "a0e onl seen pro!ra5s t"at 2se literal 0al2es (n25bers. b2t rat"er t"an send it dire3tl to t"e +rintln 12n3tion we assi!n it to a 0ariable instead. ?ariables in Go are 3reated b 1irst 2sin! t"e var /e word.+rintln5x6 8 'oti3e t"at t"e strin! literal 1ro5 t"e ori!inal pro!ra5 still appears in t"is pro!ra5. .e main import 34mt3 4unc main56 7 var x strin. ."is distin3tion is i5portant be3a2se (as t"eir na5e wo2ld s2!!est) 0ariables 3an 3"an!e t"eir 0al2e t"ro2!"o2t t"e li1eti5e o1 a pro!ra5.) and 1inall assi!nin! a 0al2e to t"e 0ariable (0ello 1orld). E 30ello 1orld3 4mt.e main import 34mt3 4unc main56 7 var x strin.) b2t s23" pro!ra5s arenHt parti32larl 2se12l.+rintln5x6 8 ?ariables in Go are si5ilar to 0ariables in al!ebra b2t t"ere are so5e s2btle di11eren3es( 9irst w"en we see t"e E s 5bol we "a0e a tenden3 to read t"at as Ix eF2als t"e strin! =ello WorldJ."e last step is optional so an alternati0e wa o1 writin! t"e pro!ra5 wo2ld be li/e t"is( pac&a."ereHs not"in! wron! wit" readin! o2r pro!ra5 t"at wa . . ."is 3"apter will explore 0ariables in 5ore detail.e main import 34mt3 4unc main56 7 var x strin. wit" a spe3i1i3 t pe and an asso3iated na5e. t"e t pe (strin. . et3. . DetHs 3"an!e t"e pro!ra5 we wrote in 3"apter 2 so t"at it 2ses a 0ariable( pac&a.r r2nnin! t"e 1ollowin!( pac&a. 4 0ariable is a stora!e lo3ation. x E 34irst3 2$ . t"en spe3i1 in! t"e 0ariable na5e (x).

(Sin3e o2 are assi!nin! a strin! literal.+rintln5x6 x E x B 3second3 4mt."e 3o5piler 3an also do in1eren3e wit" t"e var state5ent( var x E 30ello 1orld3 ."is pro!ra5 wo2ld be nonsense i1 o2 read it li/e an al!ebrai3 t"eore5.) . (Ot"er operators 3an be 2sed t"e sa5e wa ) 4not"er di11eren3e between Go and al!ebra is t"at we 2se a di11erent s 5bol 1or eF2alit ( EE. x E 34irst 3 4mt. 9or exa5ple( var x strin. On t"e ot"er "and( var x strin. E 3hello3 var .8 4mt."is will print true be3a2se t"e two strin!s are t"e sa5e.strin.1or5 is so 3o55on in pro!ra55in! t"at Go "as a spe3ial assi!n5ent state5ent( BE. &2t it 5a/es sense i1 o2 are 3are12l to read t"e pro!ra5 as a list o1 3o55ands. ."e ri!"t side o1 t"e E is done 1irst and t"e res2lt is t"en assi!ned to t"e le1t side o1 t"e E. We 3o2ld "a0e written x E x B 3second3 as x BE 3second3 and it wo2ld "a0e done t"e sa5e t"in!.wo eF2al si!ns next to ea3" ot"er) EE is an operator li/e B and it ret2rns a boolean."e x E x B ."e t pe is not ne3essar be3a2se t"e Go 3o5piler is able to in1er t"e t pe based on t"e literal 0al2e o2 assi!n t"e 0ariable. E 3hello3 4mt. E 3)orld3 4mt.+rintln5x EE -6 . x is !i0en t"e t pe strin.+rintln5x6 In 1a3t o2 3an e0en do t"is( var x strin. Sin3e 3reatin! a new 0ariable wit" a startin! 0al2e is so 3o55on Go also s2pports a s"orter state5ent( x :E 30ello 1orld3 'oti3e t"e : be1ore t"e E and t"at no t pe was spe3i1ied. ."is pro!ra5 s"o2ld print 4alse be3a2se hello is not t"e sa5e as )orld. (.J .+rintln5x EE -6 .+rintln5x6 ."e sa5e t"in! wor/s 1or ot"er t pes( 21 .strin. E 3hello3 var .+rintln5x6 x E 3second3 4mt. W"en we see x E x B 3second3 we s"o2ld read it as Iassi!n t"e 3on3atenation o1 t"e 0al2e o1 t"e 0ariable x and t"e strin! literal se3ond to t"e 0ariable x.

"o#e Goin! ba3/ to t"e pro!ra5 we saw at t"e be!innin! o1 t"e 3"apter( pac&a.x :E " How to Name a !ariable 'a5in! a 0ariable properl is an i5portant part o1 so1tware de0elop5ent."e Go 3o5piler doesnHt 3are w"at o2 na5e a 0ariable so t"e na5e is 5eant 1or o2r (and ot"ers) bene1it.+rintln53*.sName6 In t"is last 3ase we 2se a spe3ial wa to represent 52ltiple words in a 0ariable na5e /nown as lower 3a5el 3ase (also /now as 5ixed 3ase.e main import 34mt3 4unc main56 7 var x strin. 8i3/ na5es w"i3" 3learl des3ribe t"e 0ariableHs"e 1irst letter o1 t"e 1irst word is lower3ase.+rintln5x6 8 4not"er wa o1 writin! t"is pro!ra5 wo2ld be li/e t"is( pac&a. 'a5es 52st start wit" a letter and 5a 3ontain letters.+rintln5x6 Generall o2 s"o2ld 2se t"is s"orter 1or5 w"ene0er possible.Ns name is3< name6 or e0en( do. S2ppose we "ad t"e 1ollowin!( x :E 3*ax3 4mt.e main import 34mt3 var x strin. b25p 3aps.Ns name is3< x6 In t"is 3ase x is not a 0er !ood na5e 1or a 0ariable.+rintln53*.sName :E 3*ax3 4mt. n25bers or t"e M (2nders3ore) s 5bol. 3a5el ba3/ or "25p ba3/). .Ns name is3< do. 4 better na5e wo2ld be( name :E 3*ax3 4mt.+rintln53*. E 30ello 1orld3 4unc main56 7 22 . t"e 1irst letter o1 t"e s2bseF2ent words is 2pper3ase and all t"e ot"er letters are lower3ase. . E 30ello 1orld3

'ow s2ppose t"at we wrote t"is instead( 4unc main56 7 var x strin. Constants are basi3all 0ariables w"ose 0al2es 3annot be 3"an!ed later.+rintln5x6 8 23 .\main."e ran!e o1 pla3es w"ere o2 are allowed to 2se x is 3alled t"e s3ope o1 t"e 0ariable. E 30ello 1orld3 4unc main56 7 4mt.o:$$: unde4ined: x .+rintln5x6 8 4unc 456 7 4mt. E 30ello 1orld3 4mt.e main import 34mt3 4unc main56 7 const x strin."is 5eans t"at ot"er 12n3tions 3an a33ess t"is 0ariable( var x strin. b2t not o2tside o1 t"e5.+rintln5x6 'oti3e t"at we 5o0ed t"e 0ariable o2tside o1 t"e 5ain 12n3tion."e are 3reated in t"e sa5e wa o2 3reate 0ariables b2t instead o1 2sin! t"e var /e word we 2se t"e const /e word( pac&a. . . Constants Go also "as s2pport 1or 3onstants.8 4mt.+rintln5x6 8 4unc 456 7 4mt. It onl exists inside o1 t"e main 12n3tion. . 433ordin! to t"e lan!2a!e spe3i1i3ation IGo is lexi3all s3oped 2sin! blo3/sJ."e 4 12n3tion now "as a33ess to t"e x 0ariable.+rintln5x6 8 ..+rintln5x6 8 I1 o2 r2n t"is pro!ra5 o2 s"o2ld see an error( . S3ope 3an be a little 3on12sin! at 1irstU as we see 5ore Go exa5ples it s"o2ld be3o5e 5ore 3lear. E 30ello 1orld3 4mt. &asi3all t"is 5eans t"at t"e 0ariable exists wit"in t"e nearest 32rl bra3es 7 8 (a blo3/) in3l2din! an nested 32rl bra3es (blo3/s)."e 3o5piler is tellin! o2 t"at t"e x 0ariable inside o1 t"e 4 12n3tion doesnHt exist.

&n Exam#le Program =ereHs an exa5ple pro!ra5 w"i3" ta/es in a n25ber entered b t"e 2ser and do2bles it( pac&a.+rintln5output6 8 We 2se anot"er 12n3tion 1ro5 t"e 4mt pa3/a!e to read t"e 2ser inp2t (Scan4).nter a number: 36 var input 4loat>@ 4mt..ti5e error( . 9or exa5ple +i in t"e math pa3/a!e is de1ined as a 3onstant."is( const x strin. Problems • W"at are two wa s to 3reate a new 0ariableO 24 .+rint53.n to x Constants are a !ood wa to re2se 3o55on 0al2es in a pro!ra5 wit"o2t writin! t"e5 o2t ea3" ti5e.3 >es2lts in a 3o5pile. $efining %ulti#le !ariables Go also "as anot"er s"ort"and w"en o2 need to de1ine 52ltiple 0ariables( var 5 a E " b E $/ c E $" 6 Ese t"e /e word var (or const) 1ollowed b parent"eses wit" ea3" 0ariable on its own line.\main.e main import 34mt3 4unc main56 7 4mt..o:O: cannot assi. E 30ello 1orld3 x E 3Some other strin.Scan453P43< Iinput6 output :E input 9 4mt. 1or now all we need to /now is t"at Scan4 1ills inp2t wit" t"e n25ber we enter. Iinput will be explained in a later 3"apter.

(C E 5! # ? 6 9 "/A) Write anot"er pro!ra5 t"at 3on0erts 1ro5 1eet into 5eters. ($ 4t E /.• W"at is t"e 0al2e o1 x a1ter r2nnin!( x :E "Q x BE $O W"at is s3ope and "ow do o2 deter5ine t"e s3ope o1 a 0ariable in GoO W"at is t"e di11eren3e between var and constO Esin! t"e exa5ple pro!ra5 as a startin! point. write a pro!ra5 t"at 3on0erts 1ro5 9a"ren"eit into Celsi2s.?/@= m) • • • • 2- .

For . wit" ea3" n25ber on its own line.+rintln5>6 4mt.+rintln5F$ ? @ " > O = A $/F6 8 &2t bot" o1 t"ese pro!ra5s are prett tedio2s to write."e 4or state5ent allows 2s to repeat a list o1 state5ents (a blo3/) 52ltiple ti5es.+rintln5=6 4mt. Esin! w"at weH0e learned so 1ar we 3o2ld write t"is( pac&a.!ontrol Stru"tures 'ow t"at we /now "ow to 2se 0ariables itHs ti5e to start writin! so5e 2se12l pro!ra5s.+rintln5$/6 8 Or t"is( pac&a.+rintln5A6 4mt.+rintln5@6 4mt.e main import 34mt3 4unc main56 7 4mt.+rintln5$6 4mt.+rintln5O6 4mt.+rintln5"6 4mt.+rintln5 6 4mt. startin! 1ro5 1. W"at we need is a wa o1 doin! so5et"in! 52ltiple ti5es.e main import 34mt3 4unc main56 7 4mt. 9irst letHs write a pro!ra5 t"at 3o2nts to 1$.e main import 34mt3 4unc main56 7 i :E $ 26 .+rintln5?6 4mt. >ewritin! o2r pre0io2s pro!ra5 2sin! a 4or state5ent loo/s li/e t"is( pac&a.

"e pre0io2s pro!ra5 3o2ld also "a0e been written li/e t"is( 4unc main56 7 4or i :E $Q i RE $/Q iBB 7 2* . . . 2ntil. so exit Ot"er pro!ra55in! lan!2a!es "a0e a lot o1 di11erent t pes o1 loops (w"ile.4or i RE $/ 7 4mt. pro0idin! a 3onditional expression w"i3" is eit"er true or 4alse and 1inall s2ppl in! a blo3/ to exe32te. (W"en t"is "appens t"is is re1erred to as an in1inite loop) 4s an exer3ise lets wal/ t"ro2!" t"e pro!ra5 li/e a 3o5p2ter wo2ld( • • • • • • • • • • • Create a 0ariable na5ed i wit" t"e 0al2e 1 Is i RE $/O <es. (in t"is 3ase t"ere is not"in! a1ter t"e 1or loop so we exit t"e pro!ra5) 41ter we r2n t"e state5ents inside o1 t"e blo3/ we loop ba3/ to t"e be!innin! o1 t"e 1or state5ent and repeat step 1. . 'ot"in! le1t to do."e i E i B $ line is extre5el i5portant. Ot"erwise we N25p to t"e next line o1 o2r pro!ra5 a1ter t"e blo3/. do. I1 t"is e0al2ates to tr2e t"en we r2n t"e state5ents inside o1 t"e blo3/. ."e 1or loop wor/s li/e t"is( • • We e0al2ate (r2n) t"e expression i RE $/ (Ii less t"an or eF2al to 1$J). M) b2t Go onl "as one t"at 3an be 2sed in a 0ariet o1 di11erent wa s."en we 3reate a 4or loop b 2sin! t"e /e word 4or.+rintln5i6 i E i B $ 8 8 9irst we 3reate a 0ariable 3alled i t"at we 2se to store t"e n25ber we want to print. 1orea3". 8rint i Set i to i B $ (i now eF2als 3) M Set i to i B $ (i now eF2als 11) Is i RE $/O 'o. be3a2se wit"o2t it i RE $/ wo2ld alwa s e0al2ate to true and o2r pro!ra5 wo2ld ne0er stop. 8rint i Set i to i B $ (i now eF2als 2) Is i RE $/O <es.

Si5ilarl s2btra3tin! 1 3an be done wit" ##) We will see additional wa s o1 2sin! t"e 1or loop in later 3"apters.+rintln5i6 'ow t"e 3onditional expression also 3ontains two ot"er state5ents wit" se5i3olons between t"e5. Di/e t"is( $ odd even ? odd @ even " odd > even O odd = even A odd $/ even 9irst we need a wa o1 deter5inin! w"et"er or not a n25ber is e0en or odd. ot"erwise itHs odd. t"en we "a0e t"e 3ondition to 3"e3/ ea3" ti5e and 1inall we Iin3re5entJ t"e 0ariable. 4n eas wa to tell is to di0ide t"e n25ber b 2. So "ow do we 1ind t"e re5ainder a1ter di0ision in GoO We 2se t"e P operator. 9irst we "a0e t"e 0ariable initiali6ation. I1 state5ents 3an also "a0e else i4 parts( i4 i P EE / 7 // divisible b8 else i4 i P ? EE / 7 // divisible b. I1 state5ents also "a0e an optional else part. ot"erwise eit"er t"e blo3/ is s/ipped or i1 t"e else blo3/ is present t"at blo3/ is r2n. I1 t"e 3ondition e0al2ates to true t"en t"e blo3/ a1ter t"e 3ondition is r2n. I1 o2 "a0e not"in! le1t o0er t"en t"e n25ber is e0en. If DetHs 5odi1 t"e pro!ra5 we N2st wrote so t"at instead o1 N2st printin! t"e n25bers 1. 9or t"at we 2se t"e i4 state5ent( i4 i P EE / 7 // even 8 else 7 // odd 8 4n i4 state5ent is si5ilar to a 4or state5ent in t"at it "as a 3ondition 1ollowed b a blo3/.8 8 4mt.? 2+ . $ P eF2als $. P eF2als /. (addin! 1 to a 0ariable is so 3o55on t"at we "a0e a spe3ial operator( BB. 1$ on ea3" line it also spe3i1ies w"et"er or not t"e n25ber is e0en or odd. ? P eF2als $ and so on. 'ext we need a wa o1 3"oosin! to do di11erent t"in!s based on a 3ondition.

e0en i1 t"eir 3onditions also pass.+rintln5i< 3odd36 8 8 8 DetHs wal/ t"ro2!" t"is pro!ra5( • • • • • • • • • Create a 0ariable i o1 t pe int and !i0e it t"e 0al2e $ Is i less t"an or eF2al to $/O <es( N25p to t"e blo3/ Is t"e re5ainder o1 i V 8rint i 1ollowed b odd In3re5ent i (t"e state5ent a1ter t"e 3ondition) Is i less t"an or eF2al to $/O <es( N25p to t"e blo3/ Is t"e re5ainder o1 i V 8rint i 1ollowed b even M eF2al to /O <es( N25p to t"e i4 blo3/ eF2al to /O 'o( N25p to t"e else blo3/ . <o2Hll see it t2rn 2p e0er w"ere 1ro5 6ebra stripin! tables to partitionin! data sets.@ 8 ."e re5ainder operator. (So 1or exa5ple t"e n25ber + is di0isible b bot" 4 and 2.@ blo3/ will ne0er exe32te be3a2se t"e // divisible bblo3/ is done 1irst) 82ttin! it all to!et"er we "a0e( 4unc main56 7 4or i :E $Q i RE $/Q iBB 7 i4 i P EE / 7 4mt.+rintln53Sero36 2) . Esin! w"at weH0e learned so 1ar we 5i!"t start b doin! t"is( i4 i EE / 7 4mt. b2t t"e // divisible b."e 3onditions are 3"e3/ed top down and t"e 1irst one to res2lt in tr2e will "a0e its asso3iated blo3/ exe32ted. wit"h S2ppose we wanted to write a pro!ra5 t"at printed t"e .n!lis" na5es 1or n25bers.8 else i4 i P @ EE / 7 // divisible b. 'one o1 t"e ot"er blo3/s will exe32te. w"ile rarel seen o2tside o1 ele5entar s3"ool.+rintln5i< 3even36 8 else 7 4mt. t2rns o2t to be reall 2se12l w"en pro!ra55in!.

&2t 1or 52ltiples o1 t"ree print W9i66W instead o1 t"e n25ber and 1or t"e 52ltiples o1 1i0e print • 3$ . Problems • • • • • • W"at does t"e 1ollowin! pro!ra5 print( i :E $/ i4 i > $/ 7 4mt.+rintln53!ive36 8 Sin3e writin! a pro!ra5 in t"is wa wo2ld be prett tedio2s Go pro0ides anot"er state5ent to 5a/e t"is easier( t"e s)itch state5ent.+rintln53Tne36 8 else i4 i EE 7 4mt. I1 t"e are eF2i0alent t"en t"e state5ent(s) 1ollowin! t"e : is exe32ted.+rintln53!our36 8 else i4 i EE " 7 4mt.+rintln53!ive36 de4ault: 4mt.+rintln53U)o36 case ?: 4mt.+rintln53!our36 case ": 4mt. We 3an rewrite o2r pro!ra5 to loo/ li/e t"is( s)itch i 7 case /: 4mt."ese are t"e 5ain 3ontrol 1low state5ents. 6. 4 swit3" also s2pports a de1a2lt 3ase w"i3" will "appen i1 none o1 t"e 3ases 5at3"es t"e 0al2e.+rintln53Un&no)n Number36 8 4 swit3" state5ent starts wit" t"e /e word s)itch 1ollowed b an expression (in t"is 3ase i) and t"en a series o1 cases. . Di/e an i1 state5ent ea3" 3ase is 3"e3/ed top down and t"e 1irst one to s233eed is 3"osen.+rintln53U)o36 8 else i4 i EE ? 7 4mt.+rintln53Sero36 case $: 4mt.8 else i4 i EE $ 7 4mt. (3. )."e 0al2e o1 t"e expression is 3o5pared to t"e expression 1ollowin! ea3" case /e word.) Write a pro!ra5 t"at prints t"e n25bers 1ro5 1 to 1$$. 4dditional state5ents will be explored in later 3"apters.+rintln53Uhree36 8 else i4 i EE @ 7 4mt.+rintln53Small36 8 • Write a pro!ra5 t"at prints o2t all t"e n25bers e0enl di0isible b 3 between 1 and 1$$.+rintln53Uhree36 case @: 4mt. (7ind o1 li/e t"e else in an i1 state5ent) . et3.+rintln53Tne36 case : 4mt.36 8 else 7 4mt.+rintln53Bi.

9or n25bers w"i3" are 52ltiples o1 bot" t"ree and 1i0e print W9i66&266W. 31 .W&266W.

=ereHs an exa5ple pro!ra5 t"at 2ses arra s( 4unc main56 7 var x G"H4loat>@ xG/H E A= xG$H E A? xG H E OO xG?H E = xG@H E =? var total 4loat>@ E / 4or i :E /Q i R "Q iBB 7 total BE xGiH 8 4mt. 4rra s are a33essed in a si5ilar wa .+rintln5total / "6 8 32 .+rintln5x6 to 4mt.+rintln5x6 8 <o2 s"o2ld see t"is( G/ / / / $//H xG@H E $// s"o2ld be read Iset t"e -t" ele5ent o1 t"e arra x to 1$$J. arra s are indexed startin! 1ro5 $. In t"is 3"apter we will loo/ at t"ree 5ore b2ilt.e main import 34mt3 4unc main56 7 var x G"Hint xG@H E $// 4mt.#rrays$ Sli"es and %aps In 3"apter 3 we learned abo2t GoHs basi3 t pes.r r2nnin! t"e 1ollowin! pro!ra5( x pac&a. &rra's 4n arra is a n25bered seF2en3e o1 ele5ents o1 a sin!le t pe wit" a 1ixed len!t". In Go t"e loo/ li/e t"is( var x G"Hint is an exa5ple o1 an arra w"i3" is 3o5posed o1 .in t pes( arra s.+rintln5xG@H6 and we wo2ld !et 1$$. . sli3es and 5aps. It 5i!"t see5 stran!e t"at xG@H represents t"e -t" ele5ent instead o1 t"e 4t" b2t li/e strin!s. We 3o2ld 3"an!e 4mt.ints.

>2nnin! t"is pro!ra5 will res2lt in anot"er error( ( . 9irst t"ese 2 parts( i R " and total / " s"o2ld t"row 2p a red 1la! 1or 2s.+rintln5total / len5x66 Go a"ead and 5a/e t"ese 3"an!es and r2n t"e pro!ra5. We 2se t"e /e word ran.. 4not"er 3"an!e to t"e pro!ra5 we 3an 5a/e is to 2se a spe3ial 1or5 o1 t"e 1or loop( var total 4loat>@ E / 4or i< value :E ran. <o2 s"o2ld !et an error( ( . So we need to 3on0ert len5x6 into a 4loat>@( 4mt.e 1ollowed b t"e na5e o1 t"e 0ariable we want to loop o0er.uments ..o run tmp."is pro!ra5 3o5p2tes t"e a0era!e o1 a series o1 test s3ores. We wo2ld also need to 3"an!e bot" o1 t"ese parts.e x 7 total BE value 8 4mt. Sa we 3"an!ed t"e n25ber o1 !rades 1ro5 . t"en we 1ill 2p ea3" ele5ent wit" a !rade 'ext we set2p a 1or loop to 3o5p2te t"e total s3ore 9inall we di0ide t"e total s3ore b t"e n25ber o1 ele5ents to 1ind t"e a0era!e ."e iss2e "ere is t"at len5x6 and total "a0e di11erent t pes.o run tmp. DetHs wal/ t"ro2!" t"e pro!ra5( • • • 9irst we 3reate an arra o1 len!t" .o:$>: i declared and not used 33 .. It wo2ld be better to 2se t"e len!t" o1 t"e arra instead( var total 4loat>@ E / 4or i :E /Q i R len5x6Q iBB 7 total BE xGiH 8 4mt.o V command#line#ar.\tmp."is is an exa5ple o1 a t pe 3on0ersion..+rintln5total / 4loat>@5len5x666 .to "old o2r test 6.+rintln5total / 4loat>@5len5x666 In t"is 1or loop i represents t"e 32rrent position in t"e arra and value is t"e sa5e as xGiH. I1 o2 r2n it o2 s"o2ld see =>."is pro!ra5 wor/s.\tmp.uments .o V command#line#ar. total is a 4loat>@ w"ile len5x6 is an int. b2t Go pro0ides so5e 1eat2res we 3an 2se to i5pro0e it..>. In !eneral to 3on0ert between t pes o2 2se t"e t pe na5e li/e a 12n3tion.o:$A: invalid operation: total / " 5mismatched t-pes 4loat>@ and int6 .

Enli/e arra s t"is len!t" is allowed to 3"an! ma&e 12n3tion( x :E ma&e5GH4loat>@< "6 34 ."e Go 3o5piler wonHt allow o2 to 3reate 0ariables t"at o2 ne0er 2se.+rintln5total / 4loat>@5len5x666 4 sin!le M (2nders3ore) is 2sed to tell t"e 3o5piler t"at we donHt need t"is.. I1 o2 want to 3reate a sli3e o2 s"o2ld 2se t"e b2ilt. So5eti5es arra s li/e t"is 3an !et too lon! to 1it on one line. . Sin3e we donHt 2se i inside o1 o2r loop we need to 3"an!e it to t"is( var total 4loat>@ E / 4or M< value :E ran. In t"is 3ase x "as been 3reated wit" a len!t" o1 /."is is reF2ired b Go and it allows 2s to easil re5o0e an ele5ent 1ro5 t"e arra b 3o55entin! o2t t"e line( x :E G@H4loat>@7 A=< A?< OO< = < // =?< 8 li"es 4 sli3e is a se!5ent o1 an arra .e x 7 total BE value 8 4mt. (In t"is 3ase we donHt need t"e iterator 0ariable) Go also pro0ides a s"orter s ntax 1or 3reatin! arra s( x :E G"H4loat>@7 A=< A?< OO< = < =? 8 We no lon!er need to spe3i1 t"e t pe be3a2se Go 3an 1i!2re it o2t. Di/e arra s sli3es are indexable and "a0e a len!t". =ereHs an exa5ple o1 a sli3e( var x GH4loat>@ . so Go allows o2 to brea/ it 2p li/e t"is( x :E G"H4loat>@7 A=< A?< OO< = < =?< 8 'oti3e t"e extra trailin! < a1ter =?."e onl di11eren3e between t"is and an arra is t"e 5issin! len!t" between t"e bra3/ets.

9or exa5ple w"ile arrG/:"H ret2rns G$< <?<@<"H."is 3reates a sli3e t"at is asso3iated wit" an 2nderl in! 4loat>@ arra o1 len!t" -. Sli"e Fun"tions Go in3l2des two b2ilt.h is t"e index w"ere to end it (b2t not in3l2din! t"e index itsel1). hi.h.+rintln5slice$< slice 6 8 41ter r2nnin! t"is pro!ra5 slice$ "as G$< <?H and slice "as G$< <?<@<"H.+rintln5slice$< slice 6 8 3- . arrG/:H is t"e sa5e as arrG/:len5arr6H. append 3reates a new sli3e b ta/in! an existin! sli3e (t"e 1irst ar!25ent) and appendin! all t"e 1ollowin! ar!25ents to 12n3tions to assist wit" sli3es( append and cop-. lo) 9or 3on0enien3e we are also allowed to o5it lo). =ere is an exa5ple o1 3op ( 4unc main56 7 slice$ :E GHint7$< <?8 slice :E ma&e5GHint< 6 cop-5slice < slice$6 4mt. arrG$:@H ret2rns G <?<@H. arrG:"H is t"e sa5e as arrG/:"H and arrG:H is t"e sa5e as arrG/:len5arr6H. =ere is an exa5ple o1 append( 4unc main56 7 slice$ :E GHint7$< <?8 slice :E append5slice$< @< "6 4mt.. t"e 3an be s5aller. and alt"o2!" t"e 3an ne0er be lon!er t"an t"e arra . Sli3es are alwa s asso3iated wit" so5e arra ."e ma&e 12n3tion also allows a 3rd para5eter( x :E ma&e5GH4loat>@< "< $/6 1$ represents t"e 3apa3it o1 t"e 2nderl in! arra w"i3" t"e sli3e points to( 4not"er wa to 3reate sli3es is to 2se t"e Glo) : hi.hH expression( arr :E G"H4loat>@7$< <?<@<"8 x :E arrG/:"H is t"e index o1 w"ere to start t"e sli3e and hi. .h or e0en bot" lo) and hi.

is a strin! be3a2se t"e 5apHs /e t pe is strin. . I1 o2 were to read t"is o2t lo2d o2 wo2ld sa Ix is a 5ap o1 strin. instead o1 bein! an inte!er. .Hint xG3&e-3H E $/ 4mt.c: $ exit status Ep till now we "a0e onl seen 3o5pile.ti5e errors. 1ollowed b t"e /e t pe in bra3/ets and 1inall t"e 0al2e t pe.41ter r2nnin! t"is pro!ra5 slice$ "as G$< <?H and slice "as G$< H.+rintln5x6 <o2 s"o2ld see an error si5ilar to t"is( panic: runtime error: assi. ..+rintln5xG3&e-3H6 I1 o2 r2n t"is pro!ra5 o2 s"o2ld see $/ displa ed. We s"o2ld "a0e written t"is( x :E ma&e5mapGstrin. We 3an also 3reate 5aps wit" a /e t pe o1 int( 36 .o:O B/x@d . . ."is is an exa5ple o1 a r2nti5e error. a "as" table or a di3tionar . 4lso /nown as an asso3iati0e arra ..ti5e errors "appen w"en o2 tr to 3o5pile t"e pro!ra5.J Di/e arra s and sli3es 5aps 3an be a33essed 2sin! bra3/ets. b2t sin3e slice "as roo5 1or onl two ele5ents onl t"e 1irst two ele5ents o1 slice$ are 3opied.main C:/Users/W%*:N:'$/Wpp%ata/. %a#s 4 5ap is an 2nordered 3olle3tion o1 /e .o/src/p&.runtime. w"ile 3o5pile."e 3ontents o1 slice$ are 3opied into slice . r2nti5e errors "appen w"en o2 r2n t"e pro!ra5.Hint6 xG3&e-3H E $/ 4mt.r r2nnin! t"e 1ollowin! pro!ra5( var x nil map .ocal/Uemp/ /bindi t >A@AO$O//.0al2e pairs. 4s t"e na5e wo2ld i5pl .Hint .oroutine $ Grunnin.H: main.nment to entr. 5aps are 2sed to loo/ 2p a 0al2e b its asso3iated /e ./runtime/proc."e proble5 wit" o2r pro!ra5 is t"at 5aps "a0e to be initiali6ed be1ore t"e 3an be 2sed.main56 main.oroutine Gs-scallH: created b. =ereHs an exa5ple o1 a 5ap in Go( var x mapGstrin.s to ints."e 5ap t pe is represented b t"e /e word map."e state5ent xG3&e-3H E $/ is si5ilar to w"at we saw wit" arra s b2t t"e /e .

6 elementsG303H E 30-dro.Hstrin. and wit" an arra t"at wo2ld i5pl t"ere 52st be an xG/ delete 12n3tion( delete5x< $6 DetHs loo/ at an exa5ple pro!ra5 t"at 2ses a 5ap( pac&a.+rintln5xG$H6 .en3 elementsG3T3H E 3Tx-. S2ppose we tried to loo/ 2p an ele5ent t"at doesnHt exist( elements 4mt.+rintln5name< o&6 433essin! an ele5ent o1 a 5ap 3an ret2rn two 0al2es instead o1 N2st one. .+rintln5elementsG3.e3"ni3all a 5ap ret2rns t"e 6ero 0al2e 1or t"e 0al2e t pe (w"i3" 1or strin!s is t"e e5pt strin!).i3H6 8 is a 5ap t"at represents t"e 1irst 1$ 3"e5i3al ele5ents indexed b t"eir s 5bol.en3 elementsG30e3H E 30elium3 elementsG3. . 9irst t"e len!t" o1 a 5ap (1o2nd b doin! len5x6) 3an 3"an!e as we add new ite5s to it.ithium3 elementsG3Be3H E 3Ber-llium3 elementsG3B3H E 3Boron3 elementsG3C3H E 3Carbon3 elementsG3N3H E 3Nitro. .x :E ma&e5mapGintHint6 xG$H E $/ 4mt. b2t 5aps donHt "a0e t"is reF2ire5ent. t"e se3ond tells 2s w"et"er or not t"e loo/2p was s233ess12l.i3H E 3."e 1irst 0al2e is t"e res2lt o1 t"e loo/2p. a1ter xG$H E $/ it "as a len!t" o1 1. In Go we o1ten see 3ode li/e t"is( i4 name< o& :E elementsG3Un3HQ o& 7 3* . W"en 1irst 3reated it "as a len!t" o1 $.+rintln5elementsG3Un3H6 I1 o2 r2n t"is o2 s"o2ld see not"in! ret2rned."is is a 0er 3o55on wa o1 2sin! 5aps( as a loo/2p table or a di3tionar . Se3ond 5aps are not seF2ential. We 3an also delete ite5s 1ro5 a 5ap 2sin! t"e b2ilt. We "a0e xG$H."is loo/s 0er 523" li/e an arra b2t t"ere are a 1ew di11eren3es.en3 elementsG3!3H E 3!luorine3 elementsG3Ne3H E 3Neon3 4mt.e main import 34mt3 4unc main56 7 elements :E ma&e5mapGstrin. 4lt"o2!" we 3o2ld 3"e3/ 1or t"e 6ero 0al2e in a 3ondition (elementsG3Un3H EE 33) Go pro0ides a better wa ( name< o& :E elementsG3Un3H 4mt.

i3: mapGstrin. DetHs 5odi1 o2r pro!ra5 so t"at instead o1 N2st storin! t"e na5e o1 t"e ele5ent we store its standard state (state at roo5 te5perat2re) as well( 4unc main56 7 elements :E mapGstrin.as3< 8< 3.Hstrin.as3< 8< 3+ .Hstrin.7 3name3:3Carbon3< 3state3:3solid3< 8< 3N3: mapGstrin.Hstrin.Hstrin.7 3name3:3Boron3< 3state3:3solid3< 8< 3C3: mapGstrin.7 3name3:3Nitro.en3< 3!3: 3!luorine3< 3Ne3: 3Neon3< 8 @aps are also o1ten 2sed to store !eneral in1or5ation.en3< 3T3: 3Tx-.HmapGstrin.7 3name3:3Ber-llium3< 3state3:3solid3< 8< 3B3: mapGstrin. t"en i1 itHs s233ess12l we r2n t"e 3ode inside o1 t"e blo3/.i3: 3.+rintln5name< o&6 9irst we tr to !et t"e 0al2e 1ro5 t"e 5ap.Hstrin.ithium3< 3Be3: 3Ber-llium3< 3B3: 3Boron3< 3C3: 3Carbon3< 3N3: 3Nitro.7 3name3:3.en3< 3state3:3.Hstrin.en3< 3state3:3.7 303: mapGstrin.Hstrin.8 4mt.en3< 3state3:3.Hstrin.7 303: 30-dro.as3< 8< 30e3: mapGstrin.Hstrin.7 3name3:3Tx-.7 3name3:30elium3< 3state3:3.ithium3< 3state3:3solid3< 8< 3Be3: mapGstrin.7 3name3:30-dro. Di/e we saw wit" arra s t"ere is also a s"orter wa to 3reate 5aps( elements :E mapGstrin.as3< 8< 3T3: mapGstrin.en3< 30e3: 30elium3< 3.Hstrin.

+rintln5elG3name3H< elG3state3H6 8 mapGstrin."e o2ter 5ap is 2sed as a loo/2p table based on t"e ele5entHs s 5bol. We now "a0e a 5ap o1 strin!s to 5aps o1 strin!s to strin!s. in 3"apter ) we will see a better wa to store str23t2red in1or5ation.Hstrin. Problems • • • =ow do o2 a33ess t"e 4t" ele5ent o1 an arra or sli3eO W"at is t"e len!t" o1 a sli3e 3reated 2sin!( ma&e5GHint< ?< A6O Gi0en t"e arra ( x :E G>Hstrin. to mapGstrin.i3HQ o& 7 4mt..73a3<3b3<3c3<3d3<3e3<3438 w"at wo2ld xG :"H !i0e o2O • • • • • • Write a pro!ra5 t"at 1inds t"e s5allest n25ber in t"is list( x :E GHint7 @=<A><=><>=< "O<= <>?<O/< ?O<?@<=?< O< $A<AO< A<$O< 8 3) . 4lt"o2!" 5aps are o1ten 2sed li/e t"is.as3< 8 'oti3e t"at t"e t pe o1 o2r 5ap "as 3"an!ed 1ro5 mapGstrin. w"ile t"e inner 5aps are 2sed to store !eneral in1or5ation abo2t t"e ele5ents. .as3< 8< 8 i4 el< o& :E elementsG3.7 3name3:3Neon3< 3state3:3.Hstrin.Hstrin.7 3name3:3!luorine3< 3state3:3.3!3: 8< 3Ne3: mapGstrin.Hstrin.HmapGstrin.

e5xs GH4loat>@6 4loat>@ 7 panic53Not :mplemented36 8 92n3tions start wit" t"e /e word 4unc.+rintln5total / 4loat>@5len5xs666 8 .Fun"tions 4 12n3tion is an independent se3tion o1 3ode t"at 5aps 6ero or 5ore inp2t para5eters to 6ero or 5ore o2tp2t para5eters. 1ollowed b t"e 12n3tionHs na5e.e 12n3tion will need to ta/e in a sli3e o1 4loat>@s and ret2rn one 4loat>@. so its an ideal 3andidate 1or de1inition as a 12n3tion. Insert t"is be1ore t"e main 12n3tion( 4unc avera. 92n3tions (also /nown as pro3ed2res or s2bro2tines) are o1ten represented as a bla3/ box( (t"e bla3/ box represents t"e 12n3tion) Entil now t"e pro!ra5s we "a0e written in Go "a0e 2sed onl one 12n3tion( 4unc main56 78 We will now be!in writin! pro!ra5s t"at 2se 5ore t"an one 12n3tion. 41ter t"e 4$ . O2r 12n3tion "as one para5eter (t"e list o1 s3ores) t"at we na5ed xs."is pro!ra5 3o5p2tes t"e a0era!e o1 a series o1 n25bers. . . (our e"ond Fun"tion >e5e5ber t"is pro!ra5 1ro5 3"apter 6( 4unc main56 7 xs :E GH4loat>@7A=<A?<OO<= <=?8 total :E /."e avera./ 4or M< v :E ran."e para5eters (inp2ts) o1 t"e 12n3tion are de1ined li/e t"is( name t-pe< name t-pe< X.e xs 7 total BE v 8 4mt. 9indin! t"e a0era!e li/e t"is is a 0er !eneral proble5.

para5eters we p2t t"e ret2rn t pe. Colle3ti0el t"e para5eters and t"e ret2rn t pe are /nown as t"e 12n3tionHs si!nat2re. .e5someTtherName66 8 4nd o2r pro!ra5 wo2ld still wor/.+rintln5x6 8 4unc main56 7 x :E " 456 8 We need to eit"er do t"is( 41 . 'ow lets ta/e t"e 3ode 1ro5 o2r 5ain 12n3tion and 5o0e it into o2r a0era!e 12n3tion( 4unc avera. • 92n3tions donHt "a0e a33ess to an t"in! in t"e 3allin! 12n3tion./ 4or M< v :E ran. rat"er t"an tr in! to i5ple5ent t"e entire t"in! in one lar!e 12n3tion 3alled panic w"i3" 3a2ses a r2n ti5e error.+rintln to be a return instead. 9or exa5ple we 3o2ld "a0e done t"is( 4unc main56 7 someTtherName :E GH4loat>@7A=<A?<OO<= <=?8 4mt. In t"is bod we in0o/e a b2ilt."e na5es o1 t"e para5eters donHt "a0e to 5at3" in t"e 3allin! 12n3tion. 4 1ew t"in!s to /eep in 5ind( • . .+rintln5avera.e5xs66 8 >2nnin! t"is pro!ra5 s"o2ld !i0e o2 exa3tl t"e sa5e res2lt as t"e ori!inal. @odi1 main to loo/ li/e t"is( 4unc main56 7 xs :E GH4loat>@7A=<A?<OO<= <=?8 4mt.e xs 7 total BE v 8 return total / 4loat>@5len5xs66 8 'oti3e t"at we 3"an!ed t"e 4mt.+rintln5avera.e5xs GH4loat>@6 4loat>@ 7 total :E /."is wonHt wor/( 4unc 456 7 4mt."e ret2rn state5ent 3a2ses t"e 12n3tion to i55ediatel stop and ret2rn t"e 0al2e a1ter it to t"e 12n3tion t"at 3alled t"is one. (WeHll see 5ore abo2t pani3 later in t"is 3"apter) Writin! 12n3tions 3an be di11i32lt so itHs a !ood idea to brea/ t"e pro3ess into 5ana!eable 3"2n/s. 9inall we "a0e t"e 12n3tion bod w"i3" is a series o1 state5ents between 32rl bra3es.

+rintln5x6 8 4unc main56 7 456 8 • 92n3tions are b2ilt 2p in a Ista3/J.+rintln54$566 8 4unc 4$56 int 7 return 4 56 8 4unc 4 56 int 7 return $ 8 We 3o2ld 0is2ali6e it li/e t"is( .4unc 45x int6 7 4mt.+rintln5x6 8 4unc main56 7 x :E " 45x6 8 Or t"is( var x int E " 4unc 456 7 4mt. • • • • We 3an also na5e t"e ret2rn t pe( 4unc 4 56 5r int6 7 r E $ return 8 Returning %ulti#le !alues Go is also 3apable o1 ret2rnin! 52ltiple 0al2es 1ro5 a 12n3tion( 4unc 456 5int< int6 7 return "< > 8 4unc main56 7 42 . S2ppose we "ad t"is pro!ra5( 4unc main56 7 4mt.a3" ti5e we 3all a 12n3tion we p2s" it onto t"e 3all sta3/ and ea3" ti5e we ret2rn 1ro5 a 12n3tion we pop t"e last 12n3tion o11 o1 t"e sta3/.

@2ltiple 0al2es are o1ten 2sed to ret2rn an error 0al2e alon! wit" t"e res2lt (x< err :E 456). We in0o/e t"e 12n3tion li/e an ot"er 12n3tion ex3ept we 3an pass as 5an ints as we want. or a boolean to indi3ate s233ess (x< o& :E 456). 3"an!e t"e expression a1ter t"e ret2rn so t"at it 3ontains 52ltiple expressions separated b < and 1inall 3"an!e t"e assi!n5ent state5ent so t"at 52ltiple 0al2es are on t"e le1t side o1 t"e :E or E. !ariadi" Fun"tions .+rintln 12n3tion is i5ple5ented( 4unc +rintln5a .... . (."e spe3ial inter4ace78 t pe will be dis32ssed in 5ore detail in 3"apter )) We 3an also pass a sli3e o1 ints b 1ollowin! t"e sli3e wit" ..s ..( 4unc main56 7 xs :E GHint7$< <?8 4mt.inter4ace786 5n int< err error6 . be1ore t"e t pe na5e o1 t"e last para5eter o2 3an indi3ate t"at it ta/es 6ero or 5ore o1 t"ose para5eters.+rintln5add5$< <?66 8 & 2sin! ."is is pre3isel "ow t"e 4mt.:E 456 ."ree 3"an!es are ne3essar ( 3"an!e t"e ret2rn t pe to 3ontain 52ltiple t pes separated b <..8 x< .int6 int 7 total :E / 4or M< v :E ran.66 8 Closure It is possible to 3reate 12n3tions inside o1 12n3tions( 4unc main56 7 add :E 4unc5x< .. In t"is 3ase we ta/e 6ero or 5ore ints."ere is a spe3ial 1or5 a0ailable 1or t"e last para5eter in a Go 12n3tion( 4unc add5ar.s 7 total BE v 8 return total 8 4unc main56 7 4mt."e +rintln 12n3tion ta/es an n25ber o1 0al2es o1 an t pe.int6 int 7 return x B 8 43 .e ar...+rintln5add5xs..

.+rintln5next. 4 12n3tion li/e t"is to!et"er wit" t"e non. W"en o2 3reate a lo3al 12n3tion li/e t"is it also "as a33ess to ot"er lo3al 0ariables (re5e5ber s3ope 1ro5 3"apter 4)( 4unc main56 7 x :E / increment :E 4unc56 int 7 xBB return x 8 4mt.8 add 4mt. In t"is 3ase increment and t"e 0ariable x 1or5 t"e 3los2re.ven2enerator56 4unc56 uint 7 i :E uint5/6 return 4unc56 5ret uint6 7 ret E i i BE return 8 8 4unc main56 7 next.ven2enerator Re"ursion 9inall a 12n3tion is able to 3all itsel1.ven :E ma&e."is is w" t"e 1irst ti5e we 3all increment we see 1 displa ed. 9or exa5ple "ereHs "ow we 5i!"t !enerate all t"e e0en n25bers( 4unc ma&e. One wa to 2se 3los2re is b writin! a 12n3tion w"i3" ret2rns anot"er 12n3tion w"i3" G w"en 3alled G 3an !enerate a seF2en3e o1 n25bers. b2t t"e se3ond ti5e we 3all it we see 2 displa ed.ven566 // 4mt.+rintln5add5$<$66 is a lo3al 0ariable t"at "as t"e t pe 4unc5int< int6 int (a 12n3tion t"at ta/es two ints and ret2rns an int). =ere is one wa to 3o5p2te t"e 1a3torial o1 a n25ber( 4unc 4actorial5x uint6 uint 7 44 .+rintln5next. ma&e.lo3al 0ariables it re1eren3es is /nown as a 3los2re.a3" ti5e itHs 3alled it adds 2 to t"e lo3al i 0ariable w"i3" G 2nli/e nor5al lo3al 0ariables G persists between 3alls.+rintln5increment566 4mt."is x 0ariable 3an be a33essed and 5odi1ied b t"e increment 12n3tion.+rintln5increment566 8 increment adds 1 to t"e 0ariable x w"i3" is de1ined in t"e main 12n3tionHs s3ope.+rintln5next.ven566 // @ 8 ret2rns a 12n3tion w"i3" !enerates e0en n25bers.ven566 // / 4mt.ven2enerator56 4mt. . .

In order to better 2nderstand "ow t"is 12n3tion wor/s.+rintln53 nd36 8 4unc main56 7 de4er second56 4irst56 8 . $efer) Pani" * Re"o+er Go "as a spe3ial state5ent 3alled de4er w"i3" s3"ed2les a 12n3tion 3all to be r2n a1ter t"e 12n3tion 3o5pletes.e main import 34mt3 4unc 4irst56 7 4mt. Consider t"e 1ollowin! exa5ple( pac&a. (x is 2) 9ind t"e 1a3torial o1 x Y $ o o Is x EE /O 'o. &asi3all de1er 5o0es t"e 3all to second to 4- . i1 state5ents. 0ariables and si5ple 12n3tions. @ost people will 1ind 12n3tional pro!ra55in! 5ore di11i32lt to 2nderstand t"an an approa3" based on 1or loops. lets wal/ t"ro2!" 4actorial5 6( 4actorial • • Is x EE /O 'o."is pro!ra5 prints $st 1ollowed b t"e end o1 t"e 12n3tion( 4unc main56 7 4irst56 nd. o • ret2rn $ 9 $ 9 $ ret2rn Clos2re and re32rsion are power12l pro!ra55in! te3"niF2es w"i3" 1or5 t"e basis o1 a paradi!5 /nown as 12n3tional pro!ra55in!. ret2rn 1.+rintln53$st36 8 4unc second56 7 4mt. (x is 1) 9ind t"e 4actorial o1 x Y $  Is x EE /O <es.i4 x EE / 7 return $ 8 8 return x 9 4actorial5x#$6 3alls itsel1. w"i3" is w"at 5a/es t"is 12n3tion re32rsi0e.

et3. (=en3e t"e na5e Ipani3J) 46 . We 3an "andle a recover 12n3tion. 1or!ettin! to initiali6e a 5ap. (2) i1 o2r 12n3tion "ad 52ltiple ret2rn state5ents (per"aps one in an i4 and one in an else) Close will "appen be1ore bot" o1 t"e5 and (3) de1erred 12n3tions are r2n e0en i1 a r2n. Wit" de4er( de4er 4< M :E os. 9or exa5ple w"en we open a 1ile we need to 5a/e s2re to 3lose it later.Close56 ."is "as 3 ad0anta!es( (1) it /eeps o2r Close 3all near o2r Tpen 3all so its easier to 2nderstand.e main import 34mt3 4unc main56 7 panic53+WN:C36 str :E recover56 4mt.e main import 34mt3 4unc main56 7 de4er 4unc56 7 str :E recover56 4mt. We 5i!"t be te5pted to 2se it li/e t"is( pac&a.ti5e pani3 o332rs. recover stops t"e pani3 and ret2rns t"e 0al2e t"at was passed to t"e 3all to panic.Tpen54ilename6 de4er 4.arlier we 3reated a 12n3tion t"at 3alled t"e panic 12n3tion to 3a2se a r2n ti5e error.ti5e pani3 wit" t"e b2ilt. Pani" & 'e"o(er . Instead we "a0e to pair it wit" de4er( pac&a.) or an ex3eptional 3ondition t"at t"ereHs no eas wa to re3o0er 1ro5.8 second56 is o1ten 2sed w"en reso2r3es need to be 1reed in so5e wa .+rintln5str6 8 &2t t"e 3all to recover will ne0er "appen in t"is 3ase be3a2se t"e 3all to panic i55ediatel stops exe32tion o1 t"e 12n3tion.+rintln5str6 856 panic53+WN:C36 8 4 pani3 !enerall indi3ates a pro!ra55er error (1or exa5ple atte5ptin! to a33ess an index o1 an arra t"atHs o2t o1 bo2nds.

ven2enerator as an exa5ple.Problems • • is a 12n3tion w"i3" ta/es a sli3e o1 n25bers and adds t"e5 to!et"er. write a ma&eTdd2enerator 12n3tion t"at !enerates odd n25bers. . Esin! ma&e. pani3 and re3o0erO =ow do o2 re3o0er 1ro5 a r2n. Write a re32rsi0e 12n3tion w"i3" 3an 1ind 4ib5n6.ti5e pani3O • • • 4* . 9or exa5ple hal45$6 s"o2ld ret2rn 5/< 4alse6 and hal45 6 s"o2ld ret2rn 5$< true6. W"at are de1er. W"at wo2ld its 12n3tion si!nat2re loo/ li/e in GoO Write a 12n3tion w"i3" ta/es an inte!er and "al0es it and ret2rns tr2e i1 it was e0en or 1alse i1 it was odd."e 9ibona33i seF2en3e is de1ined as( 4ib5/6 E /. 4ib5$6 E $. 4ib5n6 E 4ib5n#$6 B 4ib5n# 6. sum • Write a 12n3tion wit" one 0ariadi3 para5eter t"at 1inds t"e !reatest n25ber in a list o1 n25bers.

Pointers W"en we 3all a 12n3tion t"at ta/es an ar!25ent. Ix ret2rns a 9int (pointer to an int) be3a2se x is an int."is is w"at allows 2s to 5odi1 t"e ori!inal 0ariable."e point to so5et"in! else) & 2sin! a pointer (9int) t"e Zero 12n3tion is able to 5odi1 t"e ori!inal 0ariable. w"i3" 3an onl be !i0en anot"er 9int. 9 9inall we 2se t"e I operator to 1ind t"e address o1 a 0ariable. In t"e Zero 12n3tion x+tr is a pointer to an int. and * o#erators In Go a pointer is represented 2sin! t"e 9 (asteris/) 3"ara3ter 1ollowed b t"e t pe o1 t"e stored 0al2e. new 4not"er wa to !et a pointer is to 2se t"e ne) 12n3tion( 4+ . W"en we write 9x+tr E / we are sa in! Istore t"e int $ in t"e 5e5or lo3ation x+tr re1ers toJ. &2t w"at i1 we wanted toO One wa to do t"is is to 2se a spe3ial data t pe /nown as a pointer( 4unc Zero5x+tr 9int6 7 9x+tr E / 8 4unc main56 7 x :E " Zero5Ix6 4mt. is also 2sed to Idere1eren3eJ pointer 0ariables. (. %ere1eren3in! a pointer !i0es 2s a33ess to t"e 0al2e t"e pointer points to.+rintln5x6 // x is still " 8 In t"is pro!ra5 t"e Zero 12n3tion will not 5odi1 t"e ori!inal x 0ariable in t"e main 12n3tion. I1 we tr x+tr E / instead we will !et a 3o5piler error be3a2se x+tr is not an int itHs a 9int. The . t"at ar!25ent is 3opied to t"e 12n3tion( 4unc Zero5x int6 7 x E / 8 4unc main56 7 x :E " Zero5x6 4mt.+rintln5x6 // x is / 8 8ointers re1eren3e a lo3ation in 5e5or w"ere a 0al2e is stored rat"er t"an t"e 0al2e itsel1. . Ix in main and x+tr in Zero re1er to t"e sa5e 5e5or lo3ation.

" s[uare5Ix6 8 • Write a pro!ra5 t"at 3an swap two inte!ers (x :E $Q .+rintln59x+tr6 // x is $ 8 ta/es a t pe as an ar!25ent. wit" !reat 3are bein! needed to e0ent2all delete an t"in! 3reated wit" ne).in t pes. Q s)ap5Ix< 4) . b2t as we will see in t"e next 3"apter.4unc one5x+tr 9int6 7 9x+tr E $ 8 4unc main56 7 x+tr :E ne)5int6 one5x+tr6 4mt.:E I-6 s"o2ld !i0e o2 xE and -E$). 8ointers are rarel 2sed wit" GoHs b2ilt. Go is not li/e t"is. allo3ates eno2!" 5e5or to 1it a 0al2e o1 t"at t pe and ret2rns a pointer to it. t"e are extre5el 2se12l w"en paired wit" str23ts. ne) In so5e pro!ra55in! lan!2a!es t"ere is a si!ni1i3ant di11eren3e between 2sin! ne) and I. Problems • • • • • • • • • • =ow do o2 !et t"e 5e5or address o1 a 0ariableO =ow do o2 assi!n a 0al2e to a pointerO =ow do o2 3reate a new pointerO W"at is t"e 0al2e o1 x a1ter r2nnin! t"is pro!ra5( 4unc s[uare5x 94loat>@6 7 9x E 9x 9 9x 8 4unc main56 7 x :E $. itHs a !arba!e 3olle3ted pro!ra55in! lan!2a!e w"i3" 5eans 5e5or is 3leaned 2p a2to5ati3all w"en not"in! re1ers to it an 5ore.

66 4mt.leWrea5x$< -$< x < .+rintln5circleWrea5cx< c-< cr66 8 7eepin! tra3/ o1 all t"e 3oordinates 5a/es it di11i32lt to see w"at t"e pro!ra5 is doin! and will li/el lead to 5ista/es."e t-pe /e word introd23es a new t pe.4loat>@ E $/< $/ var cx< c-< cr 4loat>@ E /< /< " 4mt.Stru"ts and Inter)a"es 4lt"o2!" it wo2ld be possible 1or 2s to write pro!ra5s onl 2sin! GoHs b2ilt. tru"ts 4n eas wa to 5a/e t"is pro!ra5 better is to 2se a str23t.S[rt5a9a B b9b6 8 4unc rectan.a3" 1ield "as a na5e and a t pe. 4 str23t is a t pe w"i3" 3ontains na5ed 1ields.+i 9 r9r 8 4unc main56 7 var rx$< r-$ 4loat>@ E /< / var rx < r. 9or exa5ple we 3o2ld represent a Cir3le li/e t"is( t-pe Circle struct 7 x 4loat>@ .4loat>@ r 4loat>@ 8 .4loat>@6 4loat>@ 7 l :E distance5x$< -$< x$< . .in data t pes. Consider a pro!ra5 t"at intera3ts wit" s"apes( pac&a. Di/e wit" 12n3tions we 3an 3ollapse 1ields t"at "a0e t"e sa5e t pe( t-pe Circle struct 7 x< -< r 4loat>@ 8 -$ . t"e /e word struct to indi3ate t"at we are de1inin! a struct t pe and a list o1 1ields inside o1 32rl bra3es.Y -$ return math.e main import 534mt3Q 3math36 4unc distance5x$< -$< x < .4loat>@6 4loat>@ 7 a :E x Y x$ b :E .leWrea5rx$< r-$< rx < r.+rintln5rectan. ItHs 1ollowed b t"e na5e o1 t"e t pe (Circle).6 ) :E distance5x$< -$< x < -$6 return l 9 ) 8 4unc circleWrea5x< -< r 4loat>@6 4loat>@ 7 return math. at so5e point it wo2ld be3o5e F2ite tedio2s.

nil 1or pointers.+i 9 c.s.+i 9 c.x E $/ c.x< c. &e3a2se o1 t"is we wo2ld t pi3all write t"e 12n3tion li/e t"is( 4unc circleWrea5c 9Circle6 4loat>@ 7 return math./ 1or 4loats. /. We 3an do t"is in two wa s. M) We 3an also 2se t"e new 12n3tion( c :E ne)5Circle6 . 9or a struct 6ero 5eans ea3" o1 t"e 1ields is set to t"eir 3orrespondin! 6ero 0al2e (/ 1or ints. it wo2ld not 5odi1 t"e ori!inal 0ariable.Initiali*ation We 3an 3reate an instan3e o1 o2r new Cir3le t pe in a 0ariet o1 wa s( var c Circle Di/e wit" ot"er data t pes. t"is will 3reate a lo3al Cir3le 0ariable t"at is b de1a2lt set to 6ero.r6 c. 33 1or strin..-< c."is allo3ates 5e5or 1or all t"e 1ields.r9c. (9Circle) @ore o1ten we want to !i0e ea3" o1 t"e 1ields a 0al2e.+rintln5c. operator( 4mt.r9c. I1 we atte5pted to 5odi1 one o1 t"e 1ields inside o1 t"e circleWrea 12n3tion. Di/e t"is( c :E Circle7x: /< -: /< r: "8 Or we 3an lea0e o11 t"e 1ield na5es i1 we /now t"e order t"e were de1ined( c :E Circle7/< /< "8 Fields We 3an a33ess 1ields 2sin! t"e . sets ea3" o1 t"e5 to t"eir 6ero 0al2e and ret2rns a pointer.E " DetHs 5odi1 t"e circleWrea 12n3tion so t"at it 2ses a Circle( 4unc circleWrea5c Circle6 4loat>@ 7 return math.r 8 4nd 3"an!e 5ain( -1 .r 8 In 5ain we "a0e( c :E Circle7/< /< "8 4mt.+rintln5circleWrea5c66 One t"in! to re5e5ber is t"at ar!25ents are alwa s 3opied in Go.

-$6 return l 9 ) 8 main "as( r :E \ectan.x$< r.x$< r.4loat>@ 8 4unc 5r 9\ectan.x$< r.-$< r.6 ) :E distance5r.area566 .. operator( 4mt.area566 Embedded Types 4 str23tHs 1ields 2s2all represent t"e "as. DetHs do t"e sa5e t"in! 1or t"e re3tan!le( t-pe \ectan.le struct 7 x$< -$< x < .+rintln5circleWrea5Ic66 %ethods 4lt"o2!" t"is is better t"an t"e 1irst 0ersion o1 t"is 3ode. We 3o2ld do t"is( t-pe Wndroid struct 7 -2 . .r9c.+rintln5r.x < r."e re3ei0er is li/e a para5eter G it "as a na5e and a t pe G b2t b 3reatin! t"e 12n3tion in t"is wa it allows 2s to 3all t"e 12n3tion 2sin! t"e .r 8 In between t"e /e word 4unc and t"e na5e o1 t"e 12n3tion weH0e added a Ire3ei0erJ.+rintln5c.le6 area56 4loat>@ 7 l :E distance5r.a relations"ip.c :E Circle7/< /< "8 4mt.+i 9 c.Name6 8 4nd we wanted to 3reate a new Wndroid str23t.+rintln530i< m. 8 4unc 5p 9+erson6 Ual&56 7 4mt. S2ppose we "ad a person str23t( t-pe +erson struct 7 Name strin."is is 523" easier to read.-$< r. 9or exa5ple a Circle "as a radius.le7/< /< $/< $/8 is3< p. we 3an i5pro0e it si!ni1i3antl b 2sin! a spe3ial t pe o1 12n3tion /nown as a 5et"od( 4unc 5c 9Circle6 area56 4loat>@ 7 return math. we no lon!er need t"e I operator (Go a2to5ati3all /nows to pass a pointer to t"e 3ir3le 1or t"is 5et"od) and be3a2se t"is 12n3tion 3an onl be 2sed wit" Circles we 3an rena5e t"e 12n3tion to N2st area.

In o2r 3ase bot" \ectan. W"en de1ined t"is wa t"e +erson str23t 3an be a33essed 2sin! t"e t pe na5e( a :E ne)5Wndroid6 a.. . 8 We 2se t"e t pe (+erson) and donHt !i0e it a na5e. =ere is an exa5ple o1 a Shape inter1a3e( t-pe Shape inter4ace 7 area56 4loat>@ 8 Di/e a str23t an inter1a3e is 3reated 2sin! t"e t-pe /e word.+erson."is was no a33ident. 8 .area56 -3 .Shape6 4loat>@ 7 var area 4loat>@ 4or M< s :E ran. 4lso /nown as anon 5o2s 1ields.le and Circle "a0e area 5et"ods w"i3" ret2rn 4loat>@s so bot" t pes i5ple5ent t"e Shape inter1a3e. rat"er t"an an 4ndroid "as a 8erson. b2t we 3an 2se inter1a3e t pes as ar!25ents to 12n3tions( 4unc totalWrea5shapes . 4 5et"od set is a list o1 5et"ods t"at a t pe 52st "a0e in order to Ii5ple5entJ t"e inter1a3e. e5bedded t pes loo/ li/e t"is( t-pe Wndroid struct 7 +erson *odel strin."is wo2ld wor/. we de1ine a I5et"od setJ."e is. Interfa"es <o2 5a "a0e noti3ed t"at we were able to na5e t"e \ectan. Go "as a wa o1 5a/in! t"ese a33idental si5ilarities expli3it t"ro2!" a t pe /nown as an Inter1a3e. 1ollowed b a na5e and t"e /e word inter4ace. &2t instead o1 de1inin! 1ields.a relations"ip wor/s t"is wa int2iti0el ( 8eople 3an tal/. b2t we wo2ld rat"er sa an 4ndroid is a 8erson. t"ere1ore an android 3an tal/.e shapes 7 area BE s.+erson +erson *odel strin.. relations"ips li/e t"ese are 3o55onpla3e. & itsel1 t"is wo2ldnHt be parti32larl 2se12l. an android is a person.Ual&56 &2t we 3an also 3all an +erson 5et"ods dire3tl on t"e Wndroid( a :E ne)5Wndroid6 a.Ual&56 . Go s2pports relations"ips li/e t"is b 2sin! an e5bedded t pe. In bot" real li1e and in pro!ra55in!.leHs area 5et"od t"e sa5e t"in! as t"e CircleHs area 5et"od.

shapes 7 area BE s. \ectan.8 return area 8 We wo2ld 3all t"is 12n3tion li/e t"is( 4mt.e m.+rintln5totalWrea5Ic< Ir66 Inter1a3es 3an also be 2sed as 1ields( t-pe *ultiShape struct 7 shapes GHShape 8 We 3an e0en t2rn *ultiShape itsel1 into a Shape b !i0in! it an area 5et"od( 4unc 5m 9*ultiShape6 area56 4loat>@ 7 var area 4loat>@ 4or M< s :E ran.les or e0en ot"er *ultiShapes. Problems • • W"atHs t"e di11eren3e between a 5et"od and a 12n3tionO W" wo2ld o2 2se an e5bedded anon 5o2s 1ield instead o1 a nor5al na5ed 1ieldO 4dd a new 5et"od to t"e Shape inter1a3e 3alled perimeter w"i3" 3al32lates t"e peri5eter o1 a s"ape.le. • -4 . I5ple5ent t"e 5et"od 1or Circle and \ectan.area56 8 return area 8 'ow a *ultiShape 3an 3ontain Circles.

o 3reate a !oro2tine we 2se t"e /e word ."e 1irst !oro2tine is i5pli3it and is t"e 5ain 12n3tion itsel1. . 4mt. .@D web pa!es in response. It wo2ld be ideal 1or pro!ra5s li/e t"ese to be able to r2n t"eir s5aller 3o5ponents at t"e sa5e ti5e (in t"e 3ase o1 t"e web ser0er to "andle 52ltiple reF2ests).Scanln5Iinput6 8 -- . 'or5all w"en we in0o/e a 12n3tion o2r pro!ra5 will exe32te all t"e state5ents in a 12n3tion and t"en ret2rn to t"e next line 1ollowin! t"e in0o3ation. Goro2tines are li!"twei!"t and we 3an easil 3reate t"o2sands o1 t"e5. .o 1ollowed b a 12n3tion in0o3ation( pac&a. @a/in! pro!ress on 5ore t"an one tas/ si52ltaneo2sl is /nown as 3on32rren3 ."is is w" t"e 3all to t"e Scanln 12n3tion "as been in3l2dedU wit"o2t it t"e pro!ra5 wo2ld exit be1ore bein! !i0en t"e opport2nit to print all t"e n25bers.o 45i6 8 var input strin.a3" reF2est is "andled li/e a s5all pro!ra5.!on"urren"y Dar!e pro!ra5s are o1ten 5ade 2p o1 5an s5aller!ra5s. Wit" a !oro2tine we ret2rn i55ediatel to t"e next line and donHt wait 1or t"e 12n3tion to 3o5plete. 4mt. 9or exa5ple a web ser0er "andles reF2ests 5ade 1ro5 web browsers and ser0es 2p =.Scanln5Iinput6 8 . We 3an 5odi1 o2r pro!ra5 to r2n 1$ !oro2tines b doin! t"is( 4unc main56 7 4or i :E /Q i R $/Q iBB 7 .o 45/6 var input strin. Go "as ri3" s2pport 1or 3on32rren3 2sin! !oro2tines and 3"annels."e se3ond !oro2tine is 3reated w"en we 3all . Goroutines 4 !oro2tine is a 12n3tion t"at is 3apable o1 r2nnin! 3on32rrentl wit" ot"er 12n3tions.e main import 34mt3 4unc 45n int6 7 4or i :E /Q i R $/Q iBB 7 4mt. .+rintln5n< 3:3< i6 8 8 4unc main56 7 . .o 45/6."is pro!ra5 3onsists o1 two !oro2tines.

Sleep5time.*illisecond 9 amt6 8 8 4unc main56 7 4or i :E /Q i R $/Q iBB 7 .6 -6 . DetHs add so5e dela to t"e 12n3tion 2sin! time.:ntn5 "/66 time.Scanln5Iinput6 8 prints o2t t"e n25bers 1ro5 $ to 1$.6 7 4or 7 ms. =ere is an exa5ple pro!ra5 2sin! 3"annels( pac&a. E ma&e5chan strin."e !oro2tines s"o2ld now r2n si52ltaneo2sl . 4mt. 4 Channels C"annels pro0ide a wa 1or two !oro2tines to 3o552ni3ate wit" one anot"er and s n3"roni6e t"eir exe32tion.e main import 5 34mt3 3time3 6 4unc pin.er5c chan strin. waitin! between $ and 2-$ 5s a1ter ea3" one.+rintln5ms.<o2 5a "a0e noti3ed t"at w"en o2 r2n t"is pro!ra5 it see5s to r2n t"e !oro2tines in order rat"er t"an si52ltaneo2sl .+rintln5n< 3:3< i6 amt :E time.%uration5rand. .Sleep and rand.o 45i6 8 var input strin.:ntn( pac&a. :E R# c 4mt.6 time.3 8 8 4unc printer5c chan strin.Sleep5time.6 7 4or i :E /Q Q iBB 7 c R# 3pin.e main import 5 34mt3 3time3 3math/rand3 6 4unc 45n int6 7 4or i :E /Q i R $/Q iBB 7 4mt.Second 9 $6 8 8 4unc main56 7 var c chan strin.

er5c6 . Esin! a 3"annel li/e t"is s n3"roni6es t"e two !oro2tines.er5c chan strin. ms. .6 ."e pro!ra5 will now ta/e t2rns printin! Ipin!J and Ipon!J. :E R# c 5eans re3ei0e a 5essa!e and store it in ms.6 -* .er5c chanR# strin. 4mt.3 8 8 4nd 5odi1 main( 4unc main56 7 var c chan strin. . 4mt. 4dd t"is 12n3tion( 4unc atte5pts to send a 5essa!e on t"e 3"annel it will wait 2ntil printer is read to re3ei0e t"e 5essa!e. 4tte5ptin! to re3ei0e 1ro5 3 will res2lt in a 3o5piler error.ire"tion We 3an spe3i1 a dire3tion on a 3"annel t pe t"2s restri3tin! it to eit"er sendin! or re3ei0in!."e 4mt line 3o2ld also "a0e been written li/e t"is( 4mt.er5c6 . 4 3"annel t pe is represented wit" t"e /e word chan 1ollowed b t"e t pe o1 t"e t"in!s t"at are passed on t"e 3"annel (in t"is 3ase we are passin! strin!s). (t"is is /nown as blo3/in!) DetHs add anot"er sender to t"e pro!ra5 and see w"at "appens.6 7 4or i :E /Q Q iBB 7 c R# 3pon.er5c6 . Si5ilarl we 3an 3"an!e printer to t"is( 4unc printer5c R#chan strin.6 'ow c 3an onl be sent to.o pon. 9or exa5ple pin!erHs 12n3tion si!nat2re 3an be 3"an!ed to t"is( 4unc pin..+rintln5R#c6 in w"i3" 3ase we 3o2ld re5o0e t"e pre0io2s line. !+annel .o pin. c R# 3pin.Scanln5Iinput6 8 ."is pro!ra5 will print Ipin!J 1ore0er ("it enter to stop it).3.o pin.o printer5c6 var input strin.3 5eans send 3pin."e R# (le1t arrow) operator is 2sed to send and re3ei0e 5essa!es on t"e 3"annel. E ma&e5chan strin.Scanln5Iinput6 8 .o printer5c6 var input strin. W"en pin..

dire3tional 3"annel 3an be passed to a 12n3tion t"at ta/es send. :E R# c : 4mt.Second 9 ?6 8 856 .$6 case ms. .Sleep5time. b2t t"e re0erse is not tr2e.$ :E R# c$: 3"annels.$ :E R# c$: 4mt.dire3tional. I1 none o1 t"e 3"annels are read .o 4unc56 7 4or 7 c R# 34rom 3 time."e select state5ent is o1ten 2sed to i5ple5ent a ti5eo2t( select 7 case ms.+rintln53timeout36 8 -+ .6 c :E ma&e5chan strin.+rintln53*essa.e $3< ms."is pro!ra5 prints I1ro5 1J e0er 2 se3onds and I1ro5 2J e0er 3 se3onds.o 4unc56 7 4or 7 select 7 case ms. select pi3/s t"e 1irst 3"annel t"at is read and re3ei0es 1ro5 it (or sends to it).Second6: 4mt. 4 bi.+rintln5ms.Scanln5Iinput6 8 . 4mt.Second 9 6 8 856 .e 3< ms. t"e state5ent blo3/s 2ntil one be3o5es a0ailable. :E R# c : 4mt. 6 case R# or re3ei0e. Sele"t Go "as a spe3ial state5ent 3alled select w"i3" wor/s li/e a s)itch b2t 1or 3"annels( 4unc main56 7 c$ :E ma&e5chan strin.$6 case ms.+rintln53*essa. I1 5ore t"an one o1 t"e 3"annels are read t"en it rando5l pi3/s w"i3" one to re3ei0e 1ro5.6 . 6 8 8 856 var input strin.4 3"annel t"at doesnHt "a0e t"ese restri3tions is /nown as bi.Sleep5time.o 4unc56 7 4or 7 c$ R# 34rom $3 time.W4ter5time.

e 3< ms.W4ter5time."e de1a2lt 3ase "appens i55ediatel i1 none o1 t"e 3"annels are read .$6 case ms.e $3< ms. (we werenHt interested in t"e ti5e so we didnHt store it in a 0ariable) We 3an also spe3i1 a de4ault 3ase( time. 6 case R# time.3reates a 3"annel and a1ter t"e !i0en d2ration will send t"e 32rrent ti5e on it. W"at is a b211ered 3"annelO =ow wo2ld o2 3reate one wit" a 3apa3it o1 2$O -) .+rintln53*essa.$ :E R# c$: 4mt. :E R# c : 4mt.Second6: 4mt. 4 b211ered 3"annel is as n3"rono2sU sendin! or re3ei0in! a 5essa!e will not wait 2nless t"e 3"annel is alread 12ll.W4ter select 7 case ms."is 3reates a b211ered 3"annel wit" a 3apa3it o1 1. Problems • • • =ow do o2 spe3i1 t"e dire3tion o1 a 3"annel t peO Write o2r own Sleep 12n3tion 2sin! time.+rintln53timeout36 de4ault: 4mt.+rintln53*essa.W4ter. -u))ered !+annels ItHs also possible to pass a se3ond para5eter to t"e 5a/e 12n3tion w"en 3reatin! a 3"annel( c :E ma&e5chan int< $6 . read-36 8 .+rintln53nothin. 'or5all 3"annels are s n3"rono2sU bot" sides o1 t"e 3"annel will wait 2ntil t"e ot"er side is read .

#boo&/chapter$$/math3 4unc main56 7 xs :E GH4loat>@7$< <?<@8 av.o w"i3" 3ontains t"is( pac&a.6 8 'ow 3reate anot"er 1older inside o1 t"e chapter$$ 1older 3alled math.. 'earl e0er pro!ra5 weH0e seen so 1ar in3l2ded t"is line( import 34mt3 is t"e na5e o1 a pa3/a!e t"at in3l2des a 0ariet o1 12n3tions related to 1or5attin! and o2tp2t to t"e s3reen.olan. Creating Pa"kages 8a3/a!es onl reall 5a/e sense in t"e 3ontext o1 a separate pro!ra5 w"i3" 2ses t"e5.e main import 34mt3 import 3. Inside t"at 1older 3reate a 1ile 3alled main. Wit"o2t t"is separate pro!ra5 we "a0e no wa o1 2sin! t"e pa3/a!e we 3reate. we donHt "a0e to re3o5pile it e0er ti5e we 3"an!e o2r pro!ra5.e math 4unc Wvera.+rintln5av.e xs 7 total BE x 6$ . .Wvera. :E math."is /eeps o2r 12n3tion na5es s"ort and s233in3t It or!ani6es 3ode so t"at its easier to 1ind 3ode o2 want to re2se.ages Go was desi!ned to be a lan!2a!e t"at en3o2ra!es !ood so1tware en!ineerin! pra3ti3es..Pa".J 4s we saw in 3"apter * 12n3tions are t"e 1irst la er we t2rn to allow 3ode re2se.o t"at 3ontains t"is( pac&a.e5xs6 4mt. It speeds 2p t"e 3o5piler b onl reF2irin! re3o5pilation o1 s5aller 3"2n/s o1 a pro!ra5. &2ndlin! 3ode in t"is wa ser0es 3 p2rposes( 4mt • • • It red23es t"e 3"an3e o1 "a0in! o0erlappin! na5es.e5xs GH4loat>@6 4loat>@ 7 total :E 4loat>@5/6 4or M< x :E ran.olan. DetHs 3reate an appli3ation t"at will 2se a pa3/a!e we will write. Inside o1 t"is 1older 3reate a 1ile 3alled math.#boo& 3alled chapter$$. 4n i5portant part o1 "i!" F2alit so1tware is 3ode re2se G e5bodied in t"e prin3iple I%onHt >epeat <o2rsel1. 4lt"o2!" we 2se t"e pa3/a!e 4mt. Create a 1older in '/2o/src/. Go also pro0ides anot"er 5e3"anis5 1or 3ode re2se( pa3/a!es.

e math)."is will 3o5pile t"e math.#boo&/chapter$$/math3 4unc main56 7 xs :E GH4loat>@7$< <?<@8 av.o."is allows 2s to 1reel 3"an!e t"ose parts later wit"o2t "a0in! to worr abo2t brea/in! ot"er pro!ra5s./osMarch/.olan.o pro!ra5 and 3reate a lin/able obNe3t 1ile( '/2o/p&. $o"umentation 61 .#boo&/chapter$$/math. .+rintln5av..olan.o run main. • <o2 5a "a0e noti3ed t"at e0er 12n3tion in t"e pa3/a!es weH0e seen start wit" a 3apital letter. b2t itHs a lot easier i1 o2 sta wit"in t"is pattern. . In Go i1 so5et"in! starts wit" a 3apital letter t"at 5eans ot"er pa3/a!es (and pro!ra5s) are able to see it. and it 5a/es o2r pa3/a!e easier to 2se."e real math pa3/a!e is N2st math. b2t inside o1 t"e math.# boo&/chapter$$/math) W"en we i5port o2r 5at" librar we 2se its 12ll na5e (import 3.o 1ile we onl 2se t"e last part o1 t"e na5e (pac&a.".# boo&/chapter$$/math3).Wvera.e5xs6 4mt. I1 we wanted to 2se bot" libraries in t"e sa5e pro!ra5 Go allows 2s to 2se an alias( import m 3. :E m. b2t sin3e Go pa3/a!es 3an be "ierar3"i3al we are sa1e to 2se t"e sa5e na5e 1or o2r pa3/a!e."ere are wa s aro2nd t"is..8 return total / 4loat>@5len5xs66 8 Esin! a ter5inal in t"e math 1older o2 N2st 3reated r2n . <o2 s"o2ld see . ItHs a !ood pra3ti3e to onl expose t"e parts o1 o2r pa3/a!e t"at we want ot"er pa3/a!es 2sin! and "ide e0er t"in! else.a.6 8 m • • • • • • is t"e alias. I1 we "ad na5ed t"e 12n3tion avera. . (w"ere os is so5et"in! li/e )indo)s and arch is so5et"in! li/e amd>@) 'ow !o ba3/ to t"e chapter$$ 1older and r2n .. o2rs is .olan. So5e t"in!s to note( • • is t"e na5e o1 a pa3/a!e t"at is part o1 GoHs standard distrib2tion. (.e o2r main pro!ra5 wo2ld not "a0e been able to see it.olan. • 8a3/a!e na5es 5at3" t"e 1olders t"e 1all in. math • We also onl 2se t"e s"ort na5e math w"en we re1eren3e 12n3tions 1ro5 o2r librar .o install.e instead o1 Wvera.

Problems • • W" do we 2se pa3/a!esO W"at is t"e di11eren3e between an identi1ier t"at starts wit" a 3apital letter and one w"i3" doesnXtO (Wvera.Go "as t"e abilit to a2to5ati3all !enerate do325entation 1or pa3/a!es we write in a si5ilar wa to t"e standard pa3/a!e do325entation.r2n t"e . In a ter5inal r2n t"is 3o55and( .e o4 a series o4 numbers 4unc Wvera."is do325entation is also a0ailable in web 1or5 b r2nnin! t"is 3o55and( . t"en re. .odoc #httpE3:>/>/3 and enterin! t"is E>D into o2r browser( http://localhost:>/>//p&./ <o2 s"o2ld be able to browse t"ro2!" all o1 t"e pa3/a!es installed on o2r s ste5.#boo&/chapter$$/math Wvera. We 3an i5pro0e t"is do325entation b addin! a 3o55ent be1ore t"e 12n3tion( // !inds the avera. =ow wo2ld o2 do325ent t"e 12n3tions o2 3reated in Y3O • • • 62 .odoc 3o55and o2 s"o2ld see o2r 3o55ent below t"e 12n3tion de1inition.e) W"at is a pa3/a!e aliasO =ow do o2 5a/e oneO We 3opied t"e a0era!e 12n3tion 1ro5 3"apter * to o2r new pa3/a!e.e <o2 s"o2ld see in1or5ation displa ed 1or t"e 12n3tion we N2st wrote.e 0s avera. Create *in and *ax 12n3tions w"i3" 1ind t"e 5ini525 and 5axi525 0al2es in a sli3e o1 4loat>@s.olan.odoc .o install in t"e math 1older.e5xs GH4loat>@6 4loat>@ 7 I1 o2 r2n .

e5t 9testin.U6 7 var v 4loat>@ v E Wvera. . In o2r 3ase sin3e weHre testin! t"e Wvera.e 12n3tion we na5e t"e test 12n3tion UestWvera.3 t-pe testpair struct 7 values GH4loat>@ avera.e math import 3testin.o t"at 3ontains t"is( pac&a."e ..e math import 3testin.e 4loat>@ 8 var tests E GHtestpair7 63 .o test 3o55and will loo/ 1or an tests in an o1 t"e 1iles in t"e 32rrent 1older and r2n t"e5.olan.o test +WSS o& .e..U.rror53.e5GH4loat>@7$< 86 i4 v KE $. Writin! tests 1or o2r 3ode is a !ood wa to ens2re F2alit and i5pro0e reliabilit . In t"e math 1older 1ro5 chapter$$ 3reate a new 1ile 3alled mathMtest..o test <o2 s"o2ld see t"is( ( .3 4unc UestWvera." so t"atHs w"at we 3"e3/.. ItHs probabl a !ood idea to test 5an di11erent 3o5binations o1 n25bers so letHs 3"an!e o2r test pro!ra5 a little( pac&a./? s . ."< ." 7 t. so letHs 3reate so5e tests 1or t"e pa3/a!e we 5ade in t"e last 3"apter.#boo&/chapter$$/math /.ests are identi1ied b startin! a 12n3tion wit" t"e word Uest and ta/in! one ar!25ent o1 t pe 9testin.Testing 8ro!ra55in! is not eas U e0en t"e best pro!ra55ers are in3apable o1 writin! pro!ra5s t"at wor/ exa3tl as intended e0er ti5e. On3e we "a0e t"e testin! 12n3tion set2p we write tests t"at 2se t"e 3ode weHre testin!. Go in3l2des a spe3ial pro!ra5 t"at 5a/es writin! tests easier.xpected $."ere1ore an i5portant part o1 t"e so1tware de0elop5ent pro3ess is testin!.ot 3< v6 8 8 'ow r2n t"is 3o55and( . In t"is 3ase we /now t"e a0era!e o1 G$< H s"o2ld be $.

9or exa5ple. Problems • Writin! a !ood s2ite o1 tests is not alwa s eas .U6 7 4or M< pair :E ran.values< 3expected3< pair."en we loop t"ro2!" ea3" one and r2n t"e 12n3tion.avera."en we 3reate a list o1 t"ese structs (pairs).e tests 7 v :E Wvera.e 7 t.. b2t t"e pro3ess o1 writin!s tests o1ten re0eals 5ore abo2t a proble5 t"en o2 5a at 1irst reali6e.. .8 7 GH4loat>@7$< 8< $.values6 i4 v KE pair. wit" o2r Wvera.e5pair. • 64 .e< 3. .ot3< v< 6 8 8 8 .e5t 9testin." 8< 7 GH4loat>@7$<$<$<$<$<$8< $ 8< 7 GH4loat>@7#$<$8< / 8< 4unc UestWvera.rror5 3!or3< pair.e 12n3tion w"at "appens i1 o2 pass in an e5pt list (GH4loat>@78)O =ow 3o2ld we 5odi1 t"e 12n3tion to ret2rn / in t"is 3aseO Write a series o1 tests 1or t"e *in and *ax 12n3tions o2 wrote in t"e pre0io2s 3"apter. We 3reate a struct to represent t"e inp2ts and o2tp2ts 1or t"e 12n3tion."is is a 0er 3o55on wa to set2p tests (ab2ndant exa5ples 3an be 1o2nd in t"e so2r3e 3ode 1or t"e pa3/a!es in3l2ded wit" Go).avera.

It is be ond t"e s3ope o1 t"is boo/ to explain t"ese 2nderl in! te3"nolo!ies.s.s.s.s. trings Go in3l2des a lar!e n25ber o1 12n3tions to wor/ wit" strin!s in t"e strin.\eplace53aaaa3< 3a3< 3b3< // GHstrin.s.s.s. 9irst a word o1 warnin!( alt"o2!" so5e o1 t"ese libraries are 1airl ob0io2s (or "a0e been explained in pre0io2s 3"apters).o)er53U.73a3<3b3<3c3<3d3<3e38 strin."is 3"apter will ta/e a loo/ at so5e o1 t"e 5ost 3o55onl 2sed pa3/a!es in3l2ded wit" Go.Contains53test3< 3es36< // strin.Count53test3< 3t36< // true strin. 5ost real world pro!ra55in! depends on o2r abilit to inter1a3e wit" existin! libraries.SU3 strin.s.Split53a#b#c#d#e3< 3#36< // 3test3 strin.0asSu44ix53test3< 3st36< // $ strin.s.T+e !ore Pa".0as+re4ix53test3< 3te36< // true strin.s.Uo.s. 5an o1 t"e libraries in3l2ded wit" Go reF2ire spe3iali6ed do5ain spe3i1i3 /nowled!e (1or exa5ple( 3r pto!rap" ).+rintln5 // true strin.ages Instead o1 writin! e0er t"in! 1ro5 s3rat3".e main import 5 34mt3 3strin. .s3 6 4unc main56 7 4mt.\epeat53a3< "6< // 3bbaa3 strin.:ndex53test3< 3e36< // 3a#b3 strin.s pa3/a!e( pac&a.SU36< // 3U.73a3<3b38< 3#36< // EE 3aaaaa3 strin.]oin5GHstrin.UoUpper53test36< 6< 6- .

o read or write to a GHb-te or a strin. I1 o2 onl need to read 1ro5 a strin! o2 3an also 2se t"e strin."e two 5ain inter1a3es are \eader and 1riter. =ere is an exa5ple o1 "ow to read t"e 3ontents o1 a 1ile and displa t"e5 on t"e ter5inal( pac&a.12n3tion w"i3" 3opies data 1ro5 a \eader to a 1riter( 4unc Cop-5dst 1riter< src \eader6 5)ritten int>@< err error6 .e main import 5 34mt3 3os3 6 4unc main56 7 4ile< err :E the 4ile siZe 66 .o 3on0ert a strin! to a sli3e o1 b tes (and 0i3e.txt36 i4 err KE nil 7 // handle the error here return 8 de4er 4ile.Bu44er bu4. o2 3an 2se t"e Bu44er str23t 1o2nd in t"e b-tes pa3/a!e( var bu4 b-tes. 9or exa5ple t"e io pa3/a!e "as a Cop.Ne)\eader 12n3tion w"i3" is 5ore e11i3ient t"an 2sin! a b211er.Close56 // . Files * Folders . b2t 5ostl inter1a3es 2sed in ot"er pa3/a!es. <o2 3an 3on0ert it into a GHb-te b 3allin! bu4."e io pa3/a!e 3onsists o1 a 1ew 12n3tions. .Tpen53test. .5GHb-te7NtN<NeN<NsN<NtN86 In#ut . @an 12n3tions in Go ta/e \eaders or 1riters as ar!25ents.o open a 1ile in Go 2se t"e Tpen 12n3tion 1ro5 t"e os pa3/a!e.B-tes56.1rite5GHb-te53test366 4 Bu44er doesnHt "a0e to be initiali6ed and s2pports bot" t"e \eader and 1riter inter1a3es.s.0ersa) do t"is( arr :E GHb-te53test36 str :E strin. \eaders s2pport readin! 0ia t"e \ead 5et"od..6 8 So5eti5es we need to wor/ wit" strin!s as binar data. .ut#ut &e1ore we loo/ at 1iles we need to 2nderstand GoHs io pa3/a!e. 1riters s2pport writin! 0ia t"e 1rite 5et"od.

\ead!ile53test.Stat56 i4 err KE nil 7 return 8 // read the 4ile bs :E ma&e5GHb-te< stat.txt36 i4 err KE nil 7 return 8 str :E strin.SiZe566 M< err E 4ile.1riteStrin.5bs6 4mt.o !et t"e 3ontents o1 a dire3tor we 2se t"e sa5e os.e main import 5 3os3 6 4unc main56 7 4ile< err :E os.Close56 ri!"t a1ter openin! t"e 1ile to 5a/e s2re t"e 1ile is 3losed as soon as t"e 12n3tion 3o5pletes.+rintln5str6 8 =ere is "ow we 3an 3reate a 1ile( pac&a. so t"ereHs a s"orter wa to do t"is( pac&a.\ead5bs6 i4 err KE nil 7 return 8 str :E strin.stat< err :E 4ile.Close56 4ile.e main 6* .Create53test.txt36 i4 err KE nil 7 // handle the error here return 8 de4er 4ile.53test36 8 .e main import 5 34mt3 3io/ioutil3 6 4unc main56 7 bs< err :E ioutil. >eadin! 1iles is 0er 3o55on.5bs6 4mt. .+rintln5str6 8 We 2se de4er 4ile.Tpen 12n3tion b2t !i0e it a dire3tor pat" instead o1 a 1ile na5e."en we 3all t"e \eaddir 5et"od( pac&a.

s2b.) Errors Go "as a b2ilt.1olders.Close56 4ile:n4os< err :E dir.Tpen53.e main import 5 34mt3 3os3 3path/4ilepath3 6 4unc main56 7 4ilepath.e main import 3errors3 4unc main56 7 err :E errors. We 3an 3reate o2r own errors b 2sin! t"e Ne) 12n3tion in t"e errors pa3/a!e( pac&a.e36 8 6+ .1al&53.import 5 34mt3 3os3 6 4unc main56 7 dir< err :E os.Name566 8 8 O1ten we want to re32rsi0el wal/ a 1older (read t"e 1olderHs 3ontents.+rintln54i.Ne)53error messa. 1olders.\eaddir5#$6 i4 err KE nil 7 return 8 4or M< 4i :E ran.36 i4 err KE nil 7 return 8 de4er dir.3< 4unc5path strin. M).< in4o os. all t"e s2b."e 12n3tion o2 pass to 1al& is 3alled 1or e0er 1ile and 1older in t"e root 1older. . (in t"is 3ase .in t pe 1or errors t"at we "a0e alread seen (t"e error t pe).!ile:n4o< err error6 error 7 4mt. all t"e s2b.e 4ile:n4os 7 4mt.+rintln5path6 return nil 86 8 .o 5a/e t"is easier t"ereHs a 1al& 12n3tion pro0ided in t"e path/4ilepath pa3/a!e( pac&a.

or 3 in t"is 3ase) and a pointer to t"e next node. 2.e int 8 t-pe B-Name GH+erson 6) .+rintln5e.5int66 8 8 ."ere are se0eral prede1ined sortin! 12n3tions (1or sli3es o1 ints and 1loats) =ereHs an exa5ple 1or "ow to sort o2r own data( pac&a.Containers * ort In addition to lists and 5aps Go "as se0eral 5ore 3olle3tions a0ailable 2nderneat" t"e 3ontainer pa3/a!e. and 1ollowin! all t"e lin/s 2ntil we rea3" nil. WeHll ta/e a loo/ at t"e container/list pa3/a!e as an exa5ple."e 6ero 0al2e 1or a . .ist is an e5pt list (a 9.lin/ed list ea3" node will also "a0e pointers to t"e pre0io2s node. Sin3e t"is is a do2bl .e main import 534mt3 Q 3sort36 t-pe +erson struct 7 Name strin. 4 lin/ed list is a t pe o1 data str23t2re t"at loo/s li/e t"is( .Ne)). Sort ..Next56 7 4mt.e main import 534mt3 Q 3container/list36 4unc main56 7 var x list.Value. W.+ushBac&5 6 x. ?al2es are appended to t"e list 2sin! +ushBac&.a3" node o1 t"e list 3ontains a 0al2e (1."e container/list pa3/a!e i5ple5ents a do2bl .+ushBac&5?6 4or e :E x.!ront56Q e KE nilQ 3an also be 3reated 2sin! list.lin/ed x."e sort pa3/a!e 3ontains 12n3tions 1or sortin! arbitrar data."is list 3o2ld be 3reated b t"is pro!ra5( pac&a. .+ushBac&5$6 x. We loop o0er ea3" ite5 in t"e list b !ettin! t"e 1irst ele5ent. /ist .

"e Sort 12n3tion in sort ta/es a sort.e6 S)ap5i< j int6 7 thisGiH< thisGjH E thisGjH< thisGiH 8 Hashes * Cr'#togra#h' 4 "as" 12n3tion ta/es a set o1 data and red23es it to a s5aller 1ixed si6e.Name 8 4unc 5this B-Name6 S)ap5i< j int6 7 thisGiH< thisGjH E thisGjH< thisGiH 8 4unc main56 7 &ids :E GH+erson7 73]ill3<A8< 73]ac&3<$/8< 8 sort.:nter4ace reF2ires 3 5et"ods( .W.ess5i< j int6 bool 7 return thisGiH.4unc 5this B-Name6 .3r pto!rap"i3."e sort.ess and S)ap. =as" 12n3tions in Go are bro/en into two 3ate!ories( 3r pto!rap"i3 and non.e GH+erson 4unc 5this B-W.e 8 4unc 5this B-W.+rintln5&ids6 8 .en56 int 7 return len5this6 8 4unc 5this B-Name6 .W. =as"es are 1reF2entl 2sed in pro!ra55in! 1or e0er t"in! 1ro5 loo/in! 2p data to easil dete3tin! 3"an!es. Sortin! o2r list o1 people is t"en as eas as 3astin! t"e list into o2r new t pe.e main import 5 34mt3 3hash/crc? 3 6 *$ . =ereHs an exa5ple 2sin! crc? ( pac&a.Name R thisGjH.en56 int 7 return len5this6 8 4unc 5this B-W.e6 . .:nter4ace and sorts it. .o de1ine o2r own sort we 3reate a new t pe (B-Name) and 5a/e it eF2i0alent to a sli3e o1 w"at we want to sort. .ess5i< j int6 bool 7 return thisGiH.3r pto!rap"i3 "as" 12n3tions 3an be 1o2nd 2nderneat" t"e "as" pa3/a!e and in3l2de adler? .Sort5B-Name5&ids66 4mt.en. crc? . . We 3o2ld also sort b a!e b doin! t"is( t-pe B-W.e6 ."e non. crc>@ and 4nv.e R thisGjH. We t"en de1ine t"e 3 5et"ods.

Sum? 56< nil 8 4unc main56 7 h$< err :E . One 3o55on 3r pto!rap"i3 "as" 12n3tion is /nown as S=4. On3e weH0e written e0er t"in! we want we 3all Sum? 56 to ret2rn a uint? ..4unc main56 7 h :E crc? .56 h. I1 t"e Sum? 0al2e 1or bot" 1iles is t"e sa5e..txt36 i4 err KE nil 7 return 8 4mt. Gi0en t"e 3r pto!rap"i3 "as" o1 a set o1 data. I1 t"e 0al2es are di11erent t"en t"e 1iles are de1initel not t"e sa5e( pac&a.56 h. itHs "i!"l li/el (t"o2!" not 1$$R 3ertain) t"at t"e 1iles are t"e sa5e. =ereHs "ow it is 2sed( pac&a.1.+rintln5h$< h < h$ EE h 6 8 Cr pto!rap"i3 "as" 12n3tions are si5ilar to t"eir non.\ead!ile54ilename6 i4 err KE nil 7 return /< err 8 h :E crc? .et0ash54ilename strin.1rite5bs6 return h. 4 3o55on 2se 1or crc? is to 3o5pare two 1iles.3r pto!rap"i3 3o2nterparts.et0ash53test . itHs extre5el di11i32lt to deter5ine w"at 5ade t"e "as".e main import 5 34mt3 3hash/crc? 3 3io/ioutil3 6 4unc .e main import 5 34mt3 3cr-pto/sha$3 6 4unc main56 7 *1 .Ne):.+rintln5v6 8 . so we 3an write b tes to it li/e an ot"er 1riter.6 5uint? < error6 7 bs< err :E ioutil.1rite5GHb-te53test366 v :E h.txt36 i4 err KE nil 7 return 8 h < err :E .et0ash53test$."e crc? "as" obNe3t i5ple5ents t"e 1riter inter1a3e. b2t t"e "a0e t"e added propert o1 bein! "ard to re0erse."ese "as"es are o1ten 2sed in se32rit appli3ations..Ne):.Sum? 56 4mt. ..

e main import 5 3encodin./.Sum5GHb-te786 4mt.Close56 4unc client56 7 // connect to the server *2 .%ecode5Ims.+rintln5err6 8 else 7 4mt.+rintln5err6 continue 8 // handle the connection .C8 ser0er( pac&a.Ne)%ecoder5c6. . so we 2se a sli3e o1 2$ b tes instead.+rintln5err6 return 8 4or 7 // accept a connection c< err :E ln.ob3 34mt3 3net3 6 4unc server56 7 // listen on a port ln< err :E net.ob.e var ms. We will 1irst ta/e a loo/ at "ow to 3reate a ."e 5ain di11eren3e is t"at w"ereas crc? 3o5p2tes a 32 bit "as".+rintln5bs6 8 .Conn6 7 // receive the messa.1rite5GHb-te53test366 bs :E h.h :E sha$. er+ers Writin! networ/ ser0ers in Go is 0er eas . be3a2se bot" crc? and sha$ i5ple5ent t"e hash.Ne)56 h."ere is no nati0e t pe to represent a 16$ bit n25ber.+rintln53\eceived3< ms."is exa5ple is 0er si5ilar to t"e crc? one. sha$ 3o5p2tes a 16$ bit "as".6 8 8 c.6 i4 err KE nil 7 4mt. .Wccept56 i4 err KE nil 7 4mt.. strin.o handleServerConnection5c6 8 8 4unc handleServerConnection5c net. err :E .0ash inter1a3e.isten53tcp3< 3:AAAA36 i4 err KE nil 7 4mt.

c< err :E net.%ial53tcp3< 3$ O././.$:AAAA36 i4 err KE nil 7 4mt.+rintln5err6 return 8 // send the messa.e ms. :E 30ello 1orld3 4mt.+rintln53Sendin.3< ms.6 err E .ob.Ne);ncoder5c6.;ncode5ms.6 i4 err KE nil 7 4mt.+rintln5err6 8 8 c.Close56

4unc main56 7 .o server56 .o client56 var input strin. 4mt.Scanln5Iinput6


."is exa5ple 2ses t"e encodin./.ob pa3/a!e w"i3" 5a/es it eas to en3ode Go 0al2es so t"at ot"er Go pro!ra5s (or t"e sa5e Go pro!ra5 in t"is 3ase) 3an read t"e5. 4dditional en3odin!s are a0ailable in pa3/a!es 2nderneat" encodin. (li/e encodin./json) as well as in 3rd part pa3/a!es. (1or exa5ple we 3o2ld 2se labix.or./v /m.o/bson 1or bson s2pport)

=..8 ser0ers are e0en easier to set2p and 2se(
pac&a.e main import 53net/http3 Q 3io36 4unc hello5res http.\esponse1riter< re[ 9http.\e[uest6 7 res.0eader56.Set5 3Content#U-pe3< 3text/html3< 6 io.1riteStrin.5 res< FRdoct-pe html> Rhtml> Rhead> Rtitle>0ello 1orldR/title> R/head> Rbod-> 0ello 1orldK R/bod-> R/html>F< 6 8 4unc main56 7


http.0andle!unc53/hello3< hello6 http.,istenWndServe53:A///3< nil6 8

"andles a E>D ro2te (/hello) b 3allin! t"e !i0en 12n3tion. We 3an also "andle stati3 1iles b 2sin! !ileServer(
0andle!unc http.0andle5 3/assets/3< http.Strip+re4ix5 3/assets/3< http.!ileServer5http.%ir53assets366< 6< 6

."e net/rpc (re5ote pro3ed2re 3all) and net/rpc/jsonrpc pa3/a!es pro0ide an eas wa to expose 5et"ods so t"e 3an be in0o/ed o0er a networ/. (rat"er t"an N2st in t"e pro!ra5 r2nnin! t"e5)
pac&a.e main import 5 34mt3 3net3 3net/rpc3 6 t-pe Server struct 78 4unc 5this 9Server6 Ne.ate5i int>@< repl- 9int>@6 error 7 9repl- E #i return nil 8 4unc server56 7 rpc.\e.ister5ne)5Server66 ln< err :E net.,isten53tcp3< 3:AAAA36 i4 err KE nil 7 4mt.+rintln5err6 return 8 4or 7 c< err :E ln.Wccept56 i4 err KE nil 7 continue 8 .o rpc.ServeConn5c6 8 8 4unc client56 7 c< err :E rpc.%ial53tcp3< 3$ O././.$:AAAA36 i4 err KE nil 7 4mt.+rintln5err6 return 8 var result int>@ err E c.Call53Server.Ne.ate3< int>@5AAA6< Iresult6


8 4unc main56 7 .o server56 .o client56

i4 err KE nil 7 4mt.+rintln5err6 8 else 7 4mt.+rintln53Server.Ne.ate5AAA6 E3< result6 8

var input strin. 4mt.Scanln5Iinput6 8

."is pro!ra5 is si5ilar to t"e .C8 exa5ple, ex3ept now we 3reated an obNe3t to "old all t"e 5et"ods we want to expose and we 3all t"e Ne.ate 5et"od 1ro5 t"e 3lient. See t"e do325entation in net/rpc 1or 5ore details.

Parsing Command /ine &rguments
W"en we in0o/e a 3o55and on t"e ter5inal itHs possible to pass t"at 3o55and ar!25ents. WeH0e seen t"is wit" t"e .o 3o55and(
.o run m-4ile..o

r2n and 5 1ile.!o are ar!25ents. We 3an also pass 1la!s to a 3o55and(
.o run #v m-4ile..o

."e 1la! pa3/a!e allows 2s to parse ar!25ents and 1la!s sent to o2r pro!ra5. =ereHs an exa5ple pro!ra5 t"at !enerates a n25ber between $ and 6. We 3an 3"an!e t"e 5ax 0al2e b sendin! a 1la! (#maxE$//) to t"e pro!ra5(
pac&a.e main import 534mt3Q34la.3Q3math/rand36 4unc main56 7 // %e4ine 4la.s maxp :E 4la..:nt53max3< >< 3the max value36 // +arse 4la..+arse56 // 2enerate a number bet)een / and max 4mt.+rintln5rand.:ntn59maxp66 8

4n additional non,1la! ar!25ents 3an be retrie0ed wit" 4la..Wr.s56 w"i3" ret2rns a GHstrin..

'n"hroni0ation Primiti+es
."e pre1erred wa to "andle 3on32rren3 and s n3"roni6ation in Go is t"ro2!" !oro2tines and 3"annels as dis32ssed in 3"apter 1$. =owe0er Go does pro0ide 5ore traditional 52ltit"readin! ro2tines in t"e s-nc and s-nc/atomic pa3/a!es. *-

and di11i32lt to reprod23e set o1 3ir325stan3es.+rintln5i< 3end36 m. sin3e t"e 5a depend on a 0er spe3i1i3.Second6 4mt.Sleep5time. =ere is an exa5ple o1 a 52tex( pac&a. relati0el rare.Unloc&56 85i6 8 var input strin. Great 3are s"o2ld be ta/en w"en 2sin! 52texes or t"e s n3"roni6ation pri5iti0es pro0ided in t"e s-nc/atomic pa3/a!e.*utex6 4or i :E /Q i R $/Q iBB 7 .ato5i3 operations.e main import 5 34mt3 3s-nc3 3time3 6 4unc main56 7 m :E ne)5s-nc. One o1 GoHs bi!!est stren!t"s is t"at t"e 3on32rren3 1eat2res it pro0ides are 523" easier to 2nderstand and 2se properl t"an t"reads and lo3/s.%utexes 4 52tex (52tal ex3l2si0e lo3/) lo3/s a se3tion o1 3ode to a sin!le t"read at a ti5e and is 2sed to prote3t s"ared reso2r3es 1ro5 non.+rintln5i< 3start36 time.Scanln5Iinput6 8 W"en t"e 52tex (m) is lo3/ed an ot"er atte5pt to lo3/ it will blo3/ 2ntil it is 2nlo3/ed.oc&56 4mt. *6 . 4mt.. .raditional 52ltit"readed pro!ra55in! is di11i32ltU itHs eas to 5a/e 5ista/es and t"ose 5ista/es are "ard to 1ind.o 4unc5i int6 7 m.

t"ere1ore learnin! "ow to wor/ in a tea5 is 3r23ial. 9or exa5ple in t"e \ead!ile 5et"od t"ereHs a 3o55ent t"at sa s t"is( // // // // :tNs a .netC) or tr o2r "and at a lar!er proNe3t. Go is well s2ited to t"is tas/ sin3e t"e so2r3e 3ode 1or t"e entire proNe3t is 1reel a0ailable. Dearn "ow to di0ide a proNe3t into pie3es o2 3an bot" wor/ on si52ltaneo2sl .r to 2nderstand e0er line and read t"e s2pplied 3o55ents. 1ind a 1riend G 5a be a 3lass5ate G and tea5 2p on a proNe3t.. ** . 4ll o1 t"e so2r3e 3ode 1or all o1 t"e pa3/a!es is a0ailable at( "ttp(CC!olan!."ere are a lot o1 wa s to do t"is( <o2 3o2ld wor/ on 3"allen!in! pro!ra55in! proble5s 1ro5 sites li/e 8roNe3t . . ItHs no di11erent wit" pro!ra55in!. tud' the %asters 8art o1 be3o5in! a !ood artist or writer is st2d in! t"e wor/s o1 t"e 5asters. 8er"aps tr to i5ple5ent a web ser0er or write a si5ple !a5e.ho) much to read< so letNs tr."is 5et"od probabl started o2t si5pler t"an w"at it be3a5e so t"is is a !reat exa5ple o1 "ow pro!ra5s 3an e0ol0e a1ter testin! and w" itHs i5portant to s2ppl 3o55ents wit" t"ose 3"an!es. One o1 t"e best wa s to be3o5e a s/illed pro!ra55er is to st2d t"e so2r3e 3ode prod23ed b ot" but be prepared 4or the ans)er to be )ron. . &2t it wo2ld be dan!ero2s to 3on3l2de t"at t"ere1ore we are 3o5petent pro!ra55ers. Team 1# @ost real.ood but not certain bet that !ile:n4o )ill tell us so1tware proNe3ts are done in tea5s. 8ro!ra55in! is as 523" a 3ra1t as it is N2st "a0in! /nowled!e.or!Csr3Cp/!CioCio2tilCio2til. .2ler ("ttp(CCproNe3te2ler. 9or exa5ple we 5i!"t ta/e a loo/ at t"e so2r3e 3ode to t"e io/ioutil librar a0ailable at( "ttp(CC!olan!. I1 o2 3an.Next Steps We now "a0e all t"e in1or5ation we need to write 5ost Go pro!ra5s.or!Csr3Cp/!C %ake omething One o1 t"e best wa s to "one o2r s/ills is to pra3ti3e 3odin!.!o >ead t"e 3ode slowl and deliberatel . ."is 3"apter will pro0ide o2 wit" so5e s2!!estions abo2t "ow best to 5aster t"e 3ra1t o1 pro!ra55in!.

*+ . Go "as a !rowin! 3o552nit w"i3" 3an be rea3"ed 0ia t"e 5ailin! list ("ttp(CC!ro2ps. write so5e 3ode (per"aps 1ix a b2!).!oo!le.n2ts). 9ind a 3rd part librar .4not"er option is to wor/ on an open so2r3e proNe3t.3o5C!ro2pC!olan!. and s2b5it it to t"e 5aintainer.