Installers

Installs Go and a text editor.

1

• •

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.

3

Files and Folders 4 1ile is a 3olle3tion o1 data stored as a 2nit wit" a na5e."is pro3ess is iterati0e (5eanin! its done 5an ti5es) and t"e steps 2s2all o0erlap. . Di/e on Windows example. its rob2st well. it is 4 . 1or exa5ple( C:\Users\john\example.txt. a de1inite si6e (5eas2red in b tes) and an asso3iated t pe. &e3a2se o1 its wide a0ailabilit on a 0ariet o1 plat1or5s. Go is a !eneral p2rpose pro!ra55in! lan!2a!e wit" ad0an3ed 1eat2res and a 3lean s ntax. 4ll 1iles are stored in t"e sa5e wa on a 3o5p2ter( t"e all "a0e a na5e. 9or exa5ple a 1ile wit" t"e na5e hello. 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. . 1or exa5ple( /Users/john/example. 3ra1t and s3ien3e o1 writin! pro!ra5s w"i3" de1ine "ow 3o5p2ters operate.txt is t"e 1ile na5e.txt "as t"e extension txt w"i3" is 2sed to represent text2al data. 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). Go is an ideal lan!2a!e to learn as o2r 1irst pro!ra55in! lan!2a!e. @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. On OSX (and 5ost ot"er operatin! s ste5s) 1ile and 1older pat"s are represented wit" t"e / (1orward slas") 3"ara3ter. . . do325ented 3o55on librar . and its 1o32s on !ood so1tware en!ineerin! prin3iples."e 3an also 3ontain ot"er 1olders."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.txt is t"e 1ile na5e."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.. it is 3ontained in t"e 1older john. 9olders (also 3alled dire3tories) are 2sed to !ro2p 1iles to!et"er.txt. On Windows 1ile and 1older pat"s (lo3ations) are represented wit" t"e \ (ba3/slas") 3"ara3ter.Getting Started Co5p2ter pro!ra55in! is t"e art.

Enli/e Windows.3ontained in t"e 1older john. OSX does not spe3i1 a dri0e letter w"ere t"e 1ile is stored. Windows On Windows 1iles and 1olders 3an be browsed 2sin! Windows . w"i3" is in t"e 1older Users.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)( - .

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. 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. It wasnHt alwa s t"is wa . 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 2se /e boards. 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). &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. <o2 s"o2ld see a bla3/ window appear t"at loo/s li/e t"is( 6 . 5i3e and to23"s3reens to intera3t wit" 0is2al b2ttons or ot"er t pes o1 3ontrols t"at are displa ed on a s3reen. We "ad a 3on0ersation wit" t"e 3o5p2ter."e Go pro!ra55in! lan!2a!e is no di11erent.exe and "ittin! enter.

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

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

9iles 3an be sa0ed b !oin! to 9ile L Sa0e or 9ile L Sa0e 4s. . 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."e text editor 3ontains a lar!e w"ite text area w"ere text 3an be entered. <o2 3an open 1iles b !oin! to 9ile L Open and browsin! to o2r desired 1ile. =o5e to !o to t"e be!innin! o1 t"e line and . . 4s o2 wor/ in a text editor it is 2se12l to learn /e board s"ort32ts.o t"e le1t o1 t"is text area o2 3an see t"e line n25bers.Windows 9or windows t"e installer will install t"e S3ite text editor.st le newlines). and we are 2sin! windows. <o2 s"o2ld see so5et"in! li/e t"is( . =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. text is bein! inserted nor5all . <o2 3an open it b !oin! to Start L 4ll 8ro!ra5s L Go L S3ite.nd to !o to t"e end o1 t"e line • • • ) . 3ol25n 1."e 5en2s list t"e s"ort32ts to t"eir ri!"t.

ext Wran!ler text editor( Di/e S3ite on Windows .ext Wran!ler 3ontains a lar!e w"ite area w"ere text is entered. =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$ • • • .• =old down s"i1t w"ile 2sin! t"e arrow /e s (or =o5e and . 9iles 3an be sa0ed b !oin! to 9ile L Sa0e or 9ile L Sa0e 4s. 9iles 3an be opened b !oin! to 9ile L Open.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 .

(@ore in1or5ation 3an be 1o2nd at "ttp(CCwww. We will be 2sin! 0ersion 1 o1 t"e lan!2a!e.o help We will see "ow t"e are 2sed in s2bseF2ent 3"apters.o$.!olan!. 4 list o1 t"ose 3o55ands is a0ailable b t pin!( . .o version .o version <o2 s"o2ld see t"e 1ollowin!( . we need t"e Go 3o5piler./. ."e Go tool s2ite is 5ade 2p o1 se0eral di11erent 3o55ands and s2b. I1 o2 !et an error abo2t t"e 3o55and not bein! re3o!ni6ed tr restartin! o2r 3o5p2ter. <o2r 0ersion n25ber 5a be sli!"tl di11erent.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."e installer will set2p Go 1or o2 a2to5ati3all . Open 2p a ter5inal and t pe t"e 1ollowin!( . .• 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. 11 ."ere1ore be1ore we 3an write a Go pro!ra5.3o55ands.

3o5piles t"e5 into an exe32table sa0ed in a te5porar dire3tor and t"en r2ns t"e pro!ra5. .olan. . 8a3/a!es are GoHs wa o1 or!ani6in! and re2sin! 3ode. .o run main. Go pro!ra5s are read top to botto5.#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.e main import 34mt3 // this is a comment 4unc main56 7 4mt. (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/."e installer o2 2sed in 3"apter 1 3reated a 1older in o2r "o5e dire3tor na5ed 2o..#boo&/chapter .olan.xe32table appli3ations are t"e /inds o1 pro!ra5s t"at we 3an r2n dire3tl 1ro5 t"e ter5inal.o in t"e 1older we N2st 3reated."ere are two t pes o1 Go pro!ra5s( exe32tables and libraries. DetHs write one 2sin! Go.. Open 2p a new ter5inal and t pe in t"e 1ollowin!( cd 2o/src/.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.e main ."e .olan. I1 o2 didnHt see 0ello 1orld displa ed o2 5a "a0e 5ade a 5ista/e w"en t pin! in t"e pro!ra5. (li/e a boo/) . 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.0er Go pro!ra5 52st start wit" a pa3/a!e de3laration. le1t to ri!"t. (in Windows t"e end 12 ."e 1irst line sa s t"is( pac&a. 9irst 3reate a new 1older w"ere we 3an store o2r pro!ra5. .#boo& m&dir 2o/src/.Your First Program . . .o run 3o55and ta/es t"e s2bseF2ent 1iles (separated b spa3es).olan.o <o2 s"o2ld see 0ello 1orld displa ed in o2r ter5inal. Create a 1older na5ed '/2o/src/.#boo&/chapter . Di/e 5ost 3o5pilers."is is /nown as a Ipa3/a!e de3larationJ.

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. Go 5ostl doesnHt 3are abo2t w"itespa3e.+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."e 2se o1 do2ble F2otes li/e t"is is /nown as a Istrin! literalJ w"i3" is a t pe o1 IexpressionJ."e 1inal pie3e o1 o2r pro!ra5 is t"is line( 13 ."e line t"at starts wit" // is /nown as a 3o55ent.wit" . spa3es and tabs are /nown as w"itespa3e (be3a2se o2 3anHt see t"e5). (<o2 3o2ld re5o0e t"is line and t"e pro!ra5 wo2ld be"a0e in exa3tl t"e sa5e wa ) . 1or now N2st 5a/e s2re to in3l2de t"is line in an pro!ra5 o2 write. (4nd 5a in3l2de 52ltiple lines) 41ter t"is o2 see a 12n3tion de3laration( 4unc main56 7 4mt."e 3 3"ara3ter itsel1 is not part o1 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). 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!. a list o1 6ero or 5ore Ipara5etersJ s2rro2nded b parent"eses. 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). Strin!s are des3ribed in 5ore detail in t"e next 3"apter."e "a0e inp2ts. . 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. . 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. Co5p2ters represent newlines wit" a spe3ial 3"ara3ter (or se0eral 3"ara3ters). ."is 12n3tion "as no para5eters. we 2se it to 5a/e pro!ra5s easier to read."e next line is a blan/ line."e na5e main is spe3ial be3a2se itHs t"e 12n3tion t"at !ets 3alled w"en o2 exe32te t"e pro!ra5. M) o1 a de1inite len!t". We will explore libraries in 5ore detail later. s 5bols. ."e import /e word is "ow we in3l2de 3ode 1ro5 ot"er pa3/a!es to 2se wit" o2r pro!ra5. doesnHt ret2rn an t"in! and "as onl one state5ent. (. n25bers. . ."en we see t"is( import 34mt3 . In Go strin!s represent a seF2en3e o1 3"ara3ters (letters."e 4mt pa3/a!e (s"ort"and 1or 1or5at) i5ple5ents 1or5attin! 1or inp2t and o2tp2t. an optional ret2rn t pe and a Ibod J w"i3" is s2rro2nded b 32rl bra3es. 'ewlines.

+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. &a3/ to t"e 12n3tion at "and."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. . 9irst we a33ess anot"er 12n3tion inside o1 t"e 4mt pa3/a!e 3alled +rintln (t"atHs t"e 4mt.+rintln530ello 1orld36 .odoc 4mt +rintln 45on! ot"er t"in!s o2 s"o2ld see t"is( +rintln 4ormats usin. . 'e0ert"eless t"e . 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."is state5ent is 5ade o1 t"ree 3o5ponents. So5eti5es its "elp12l to deliberatel read o2r pro!ra5 o2t lo2d. 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. the de4ault 4ormats 4or its operands and )rites to standard output. 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.4mt."at 12n3tion ta/es no ar!25ents."is 12n3tion is w"at 3a2ses 0ello 1orld to be displa ed. 4t t"is point weH0e alread seen a lot o1 new ter5inolo! and o2 5a be a bit o0erw"el5ed. w"i3" re1eren3es t"e 4mt librar and 3ontains one 12n3tion 3alled main. One readin! o1 t"e pro!ra5 we N2st wrote 5i!"t !o li/e t"is( Create a new exe32table pro!ra5.e main.odoc 3o55and is extre5el 2se12l and a !ood pla3e to start w"ene0er o2 "a0e a F2estion. +rintln 5eans 8rint Dine). ."e +rintln 12n3tion does t"e real wor/ in t"is pro!ra5. :t returns the number o4 b-tes )ritten and an)rite error encountered. W"at wo2ld t"e 1iles in t"e 4mt pa3/a!e be!in wit"O 14 . . 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. <o2 3an 1ind o2t 5ore abo2t it b t pin! t"e 1ollowin! in o2r ter5inal( .

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

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

. (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."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 $.o 1ile 3ontainin! t"e 1ollowin!( pac&a./6 'oti3e t"at we 2se t"e . 9or exa5ple \n !ets repla3ed wit" a newline and \t !ets repla3ed wit" a tab 3"ara3ter. Go strin!s are 5ade 2p o1 indi0id2al b tes.+rintln53$ B $ E3< $ B $6 8 I1 o2 r2n t"e pro!ra5 and o2 s"o2ld see t"is( ( .Example DetHs write an exa5ple pro!ra5 2sin! n25bers."e di11eren3e between t"ese is t"at do2ble F2oted strin!s 3annot 3ontain newlines and t"e allow spe3ial es3ape seF2en3es.o $ B $ E 'oti3e t"at t"is pro!ra5 is 0er si5ilar to t"e pro!ra5 we wrote in 3"apter 2. ..o run main. 2s2all one 1or ea3" 3"ara3ter. DetHs tr t"e sa5e t"in! 2sin! 1loatin! point n25bers( 4mt."is expression is 5ade 2p o1 t"ree parts( t"e n25eri3 literal $ (w"i3" is o1 t pe int).+rintln53$ B $ E3< $. . t"e sa5e 12n3tion de3laration and 2ses t"e sa5e +rintln 12n3tion. t"e B operator (w"i3" represents addition) and anot"er n25eri3 literal $. In addition to addition Go "as se0eral ot"er operators( K ./ B $.e main import 34mt3 4unc main56 7 4mt. It 3ontains t"e sa5e pa3/a!e line.. 1* . >2nnin! t"is pro!ra5 will !i0e o2 t"e sa5e res2lt as be1ore. t"e sa5e i5port line. 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./ to tell Go t"at t"is is a 1loatin! point n25ber instead o1 an inte!er. 9irst 3reate a 1older 3alled chapter? and 5a/e a main.

One wa to t"in/ abo2t indexin! wo2ld be to s"ow it li/e t"is instead( 30ello 1orld3$. DetHs 5odi1 t"e pro!ra5 we 3reated earlier to test t"ese o2t( pac&a."e se3ond 3"ara3ter o1 t"e strin! =ello WorldJ.e main import 34mt3 4unc main56 7 4mt. .+rintln5len530ello 1orld366 4mt. 4lso noti3e t"at o2 see $/$ instead o1 e w"en o2 r2n t"is pro!ra5. 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.+rintln5Ktrue6 8 true6 4alse6 true6 4alse6 1+ ."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.Se0eral 3o55on operations on strin!s in3l2de 1indin! t"e len!t" o1 a strin!( len530ello 1orld36."e strin! =ello World s2b 1. <o2Hd read t"at as I. • Con3atenation 2ses t"e sa5e s 5bol as addition. and 3on3atenatin! two strin!s to!et"er( 30ello 3 B 31orld3.+rintln5true II 4mt. ."e Go 3o5piler 1i!2res o2t w"at to do based on t"e t pes o1 t"e ar!25ents. 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. (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). . so t"e strin!Hs len!t" is 11 not 1$ and t"e 3rd line "as 30ello 3 instead o1 30ello3."e strin! =ello World at 1J or I.+rintln5true JJ 4mt.+rintln530ello 1orld3G$H6 4mt.J I.+rintln5true JJ 4mt."is is be3a2se t"e 3"ara3ter is represented b a b te (re5e5ber a b te is an inte!er). Strin!s are IindexedJ startin! at $ not 1.+rintln5true II 4mt.

1 P ) and 1$2. Write a pro!ra5 t"at 3o5p2tes ? $? " L @ @" $ and prints it to t"e ter5inal.. Gi0en t"at in binar t"e lar!est 2 di!it n25ber is 11 (3).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 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 Ttr2e 1alse T1alse tr2e .>2nnin! t"is pro!ra5 s"o2ld !i0e o2( ( . 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 )).o run main.xpression ?al2e tr2e AA tr2e tr2e tr2e AA 1alse 1alse 1alse AA tr2e 1alse 1alse AA 1alse 1alse . 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.o true 4alse true true 4alse We 2s2all 2se tr2t" tables to de1ine "ow t"ese operators wor/( . (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) .

DetHs 3"an!e t"e pro!ra5 we wrote in 3"apter 2 so t"at it 2ses a 0ariable( pac&a. . ?ariables in Go are 3reated b 1irst 2sin! t"e var /e word.r r2nnin! t"e 1ollowin!( pac&a. 4 0ariable is a stora!e lo3ation.) b2t s23" pro!ra5s arenHt parti32larl 2se12l. .ariables Ep 2ntil now we "a0e onl seen pro!ra5s t"at 2se literal 0al2es (n25bers."e last step is optional so an alternati0e wa o1 writin! t"e pro!ra5 wo2ld be li/e t"is( pac&a. t"en spe3i1 in! t"e 0ariable na5e (x). t"e t pe (strin.e main import 34mt3 4unc main56 7 var x strin. et3. E 30ello 1orld3 4mt. x E 30ello 1orld3 4mt. b2t rat"er t"an send it dire3tl to t"e +rintln 12n3tion we assi!n it to a 0ariable instead."is 3"apter will explore 0ariables in 5ore detail.) and 1inall assi!nin! a 0al2e to t"e 0ariable (0ello 1orld)."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. x E 34irst3 2$ ."ereHs not"in! wron! wit" readin! o2r pro!ra5 t"at wa .+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. wit" a spe3i1i3 t pe and an asso3iated na5e. .e main import 34mt3 4unc main56 7 var x strin.o 5a/e tr2l 2se12l pro!ra5s we need to learn two new 3on3epts( 0ariables and 3ontrol 1low state5ents.e main import 34mt3 4unc main56 7 var x strin. 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. . . . strin!s.+rintln5x6 8 'oti3e t"at t"e strin! literal 1ro5 t"e ori!inal pro!ra5 still appears in t"is pro!ra5.

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.+rintln5x6 In 1a3t o2 3an e0en do t"is( var x strin. .J ."is will print true be3a2se t"e two strin!s are t"e sa5e.) . 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.+rintln5x6 . E 3)orld3 4mt. E 3hello3 var .+rintln5x EE -6 . E 3hello3 var .8 4mt.+rintln5x6 x E x B 3second3 4mt.1or5 is so 3o55on in pro!ra55in! t"at Go "as a spe3ial assi!n5ent state5ent( BE."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. (Sin3e o2 are assi!nin! a strin! literal.+rintln5x6 x E 3second3 4mt."e sa5e t"in! wor/s 1or ot"er t pes( 21 . (. We 3o2ld "a0e written x E x B 3second3 as x BE 3second3 and it wo2ld "a0e done t"e sa5e t"in!.+rintln5x EE -6 .wo eF2al si!ns next to ea3" ot"er) EE is an operator li/e B and it ret2rns a boolean. x E 34irst 3 4mt."is pro!ra5 wo2ld be nonsense i1 o2 read it li/e an al!ebrai3 t"eore5."is pro!ra5 s"o2ld print 4alse be3a2se hello is not t"e sa5e as )orld.strin."e x E x B . 9or exa5ple( var x strin. E 3hello3 4mt. On t"e ot"er "and( var x strin. (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 is !i0en t"e t pe strin."e 3o5piler 3an also do in1eren3e wit" t"e var state5ent( var x E 30ello 1orld3 . &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.strin.

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

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

+rint53.e main import 34mt3 4unc main56 7 4mt.ti5e error( ."is( const x strin.. Iinput will be explained in a later 3"apter. &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).o:O: cannot assi. E 30ello 1orld3 x E 3Some other strin.3 >es2lts in a 3o5pile. 9or exa5ple +i in t"e math pa3/a!e is de1ined as a 3onstant. Problems • W"at are two wa s to 3reate a new 0ariableO 24 .n to x Constants are a !ood wa to re2se 3o55on 0al2es in a pro!ra5 wit"o2t writin! t"e5 o2t ea3" ti5e.Scan453P43< Iinput6 output :E input 9 4mt.nter a number: 36 var input 4loat>@ 4mt. 1or now all we need to /now is t"at Scan4 1ills inp2t wit" t"e n25ber we enter. $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.

write a pro!ra5 t"at 3on0erts 1ro5 9a"ren"eit into Celsi2s.• 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. ($ 4t E /.?/@= m) • • • • 2- . (C E 5! # ? 6 9 "/A) Write anot"er pro!ra5 t"at 3on0erts 1ro5 1eet into 5eters.

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

. (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. so exit Ot"er pro!ra55in! lan!2a!es "a0e a lot o1 di11erent t pes o1 loops (w"ile. 8rint i Set i to i B $ (i now eF2als 2) Is i RE $/O <es. . M) b2t Go onl "as one t"at 3an be 2sed in a 0ariet o1 di11erent wa s.4or i RE $/ 7 4mt. Ot"erwise we N25p to t"e next line o1 o2r pro!ra5 a1ter t"e blo3/. (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."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* . . 'ot"in! le1t to do. 2ntil. 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."e i E i B $ line is extre5el i5portant. do. .+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."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). 1orea3". pro0idin! a 3onditional expression w"i3" is eit"er true or 4alse and 1inall s2ppl in! a blo3/ to exe32te."en we 3reate a 4or loop b 2sin! t"e /e word 4or. I1 t"is e0al2ates to tr2e t"en we r2n t"e state5ents inside o1 t"e blo3/.

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

8 else i4 i P @ EE / 7 // divisible b. t2rns o2t to be reall 2se12l w"en pro!ra55in!. Esin! w"at weH0e learned so 1ar we 5i!"t start b doin! t"is( i4 i EE / 7 4mt. (So 1or exa5ple t"e n25ber + is di0isible b bot" 4 and 2."e 3onditions are 3"e3/ed top down and t"e 1irst one to res2lt in tr2e will "a0e its asso3iated blo3/ exe32ted.+rintln53Sero36 2) . <o2Hll see it t2rn 2p e0er w"ere 1ro5 6ebra stripin! tables to partitionin! data sets. b2t t"e // divisible b. 'one o1 t"e ot"er blo3/s will exe32te. wit"h S2ppose we wanted to write a pro!ra5 t"at printed t"e ."e re5ainder operator. e0en i1 t"eir 3onditions also pass.@ 8 .+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/ .@ 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. w"ile rarel seen o2tside o1 ele5entar s3"ool.+rintln5i< 3even36 8 else 7 4mt.n!lis" na5es 1or n25bers.

Di/e an i1 state5ent ea3" 3ase is 3"e3/ed top down and t"e 1irst one to s233eed is 3"osen.+rintln53Tne36 8 else i4 i EE 7 4mt. (3.+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.8 else i4 i EE $ 7 4mt. 4dditional state5ents will be explored in later 3"apters.+rintln53Tne36 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. et3. ). Problems • • • • • • W"at does t"e 1ollowin! pro!ra5 print( i :E $/ i4 i > $/ 7 4mt.+rintln53Uhree36 8 else i4 i EE @ 7 4mt.+rintln53U)o36 8 else i4 i EE ? 7 4mt.+rintln53Uhree36 case @: 4mt."e 0al2e o1 t"e expression is 3o5pared to t"e expression 1ollowin! ea3" case /e word.+rintln53Small36 8 • Write a pro!ra5 t"at prints o2t all t"e n25bers e0enl di0isible b 3 between 1 and 1$$.+rintln53Sero36 case $: 4mt.+rintln53U)o36 case ?: 4mt.36 8 else 7 4mt. 6. (7ind o1 li/e t"e else in an i1 state5ent) .) Write a pro!ra5 t"at prints t"e n25bers 1ro5 1 to 1$$.+rintln53!our36 case ": 4mt. 4 swit3" also s2pports a de1a2lt 3ase w"i3" will "appen i1 none o1 t"e 3ases 5at3"es t"e 0al2e. I1 t"e are eF2i0alent t"en t"e state5ent(s) 1ollowin! t"e : is exe32ted. &2t 1or 52ltiples o1 t"ree print W9i66W instead o1 t"e n25ber and 1or t"e 52ltiples o1 1i0e print • 3$ .+rintln53!our36 8 else i4 i EE " 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. .+rintln53Bi.+rintln53!ive36 de4ault: 4mt.

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

+rintln5total / "6 8 32 .r r2nnin! t"e 1ollowin! pro!ra5( x pac&a. sli3es and 5aps.+rintln5x6 to 4mt. 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.ints. &rra's 4n arra is a n25bered seF2en3e o1 ele5ents o1 a sin!le t pe wit" a 1ixed len!t". 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. =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. 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.+rintln5xG@H6 and we wo2ld !et 1$$. arra s are indexed startin! 1ro5 $. We 3o2ld 3"an!e 4mt. . 4rra s are a33essed in a si5ilar wa .+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.

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

in ma&e 12n3tion( x :E ma&e5GH4loat>@< "6 34 . So5eti5es arra s li/e t"is 3an !et too lon! to 1it on one line. 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 Go 3o5piler wonHt allow o2 to 3reate 0ariables t"at o2 ne0er 2se. Di/e arra s sli3es are indexable and "a0e a len!t". I1 o2 want to 3reate a sli3e o2 s"o2ld 2se t"e b2ilt.+rintln5total / 4loat>@5len5x666 4 sin!le M (2nders3ore) is 2sed to tell t"e 3o5piler t"at we donHt need t"is. Enli/e arra s t"is len!t" is allowed to 3"an!e."e onl di11eren3e between t"is and an arra is t"e 5issin! len!t" between t"e bra3/ets..e x 7 total BE value 8 4mt."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 . (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. . In t"is 3ase x "as been 3reated wit" a len!t" o1 /. 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. =ereHs an exa5ple o1 a sli3e( var x GH4loat>@ .

"is 3reates a sli3e t"at is asso3iated wit" an 2nderl in! 4loat>@ arra o1 len!t" -.. =ere is an exa5ple o1 3op ( 4unc main56 7 slice$ :E GHint7$< <?8 slice :E ma&e5GHint< 6 cop-5slice < slice$6 4mt. =ere is an exa5ple o1 append( 4unc main56 7 slice$ :E GHint7$< <?8 slice :E append5slice$< @< "6 4mt. lo) 9or 3on0enien3e we are also allowed to o5it lo).h. Sli"e Fun"tions Go in3l2des two b2ilt."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. and alt"o2!" t"e 3an ne0er be lon!er t"an t"e arra . arrG$:@H ret2rns G <?<@H.h is t"e index w"ere to end it (b2t not in3l2din! t"e index itsel1). . 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 it.h or e0en bot" lo) and hi. 9or exa5ple w"ile arrG/:"H ret2rns G$< <?<@<"H. arrG:"H is t"e sa5e as arrG/:"H and arrG:H is t"e sa5e as arrG/:len5arr6H.+rintln5slice$< slice 6 8 41ter r2nnin! t"is pro!ra5 slice$ "as G$< <?H and slice "as G$< <?<@<"H.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.+rintln5slice$< slice 6 8 3- .in 12n3tions to assist wit" sli3es( append and cop-. arrG/:H is t"e sa5e as arrG/:len5arr6H. Sli3es are alwa s asso3iated wit" so5e arra . t"e 3an be s5aller. hi.

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

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

ithium3< 3Be3: 3Ber-llium3< 3B3: 3Boron3< 3C3: 3Carbon3< 3N3: 3Nitro.+rintln5name< o&6 9irst we tr to !et t"e 0al2e 1ro5 t"e 5ap.Hstrin.Hstrin.en3< 3T3: 3Tx-.as3< 8< 3T3: mapGstrin.7 3name3:3Tx-.HmapGstrin. t"en i1 itHs s233ess12l we r2n t"e 3ode inside o1 t"e blo3/.i3: 3.7 3name3:3. 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.7 3name3:30elium3< 3state3:3.7 3name3:3Carbon3< 3state3:3solid3< 8< 3N3: mapGstrin.as3< 8< 3.en3< 30e3: 30elium3< 3.7 3name3:3Nitro.as3< 8< 3+ .7 3name3:3Boron3< 3state3:3solid3< 8< 3C3: mapGstrin.8 4mt.en3< 3state3:3.Hstrin.7 3name3:30-dro.Hstrin.Hstrin.7 303: 30-dro.en3< 3state3:3.7 303: mapGstrin.en3< 3state3:3.Hstrin. Di/e we saw wit" arra s t"ere is also a s"orter wa to 3reate 5aps( elements :E mapGstrin.ithium3< 3state3:3solid3< 8< 3Be3: mapGstrin.Hstrin.as3< 8< 30e3: mapGstrin.Hstrin.en3< 3!3: 3!luorine3< 3Ne3: 3Neon3< 8 @aps are also o1ten 2sed to store !eneral in1or5ation.i3: mapGstrin.7 3name3:3Ber-llium3< 3state3:3solid3< 8< 3B3: mapGstrin.Hstrin.Hstrin.

to mapGstrin.as3< 8 'oti3e t"at t"e t pe o1 o2r 5ap "as 3"an!ed 1ro5 mapGstrin. 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. 4lt"o2!" 5aps are o1ten 2sed li/e t"is.Hstrin."e o2ter 5ap is 2sed as a loo/2p table based on t"e ele5entHs s 5bol. .HmapGstrin. in 3"apter ) we will see a better wa to store str23t2red in1or5ation.Hstrin..7 3name3:3Neon3< 3state3:3.7 3name3:3!luorine3< 3state3:3.3!3: 8< 3Ne3: mapGstrin.Hstrin.Hstrin.as3< 8< 8 i4 el< o& :E elementsG3.+rintln5elG3name3H< elG3state3H6 8 mapGstrin. We now "a0e a 5ap o1 strin!s to 5aps o1 strin!s to strin!s.i3HQ o& 7 4mt. w"ile t"e inner 5aps are 2sed to store !eneral in1or5ation abo2t t"e ele5ents.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) .

Fun"tions 4 12n3tion is an independent se3tion o1 3ode t"at 5aps 6ero or 5ore inp2t para5eters to 6ero or 5ore o2tp2t para5eters."e para5eters (inp2ts) o1 t"e 12n3tion are de1ined li/e t"is( name t-pe< name t-pe< X. Insert t"is be1ore t"e main 12n3tion( 4unc avera. so its an ideal 3andidate 1or de1inition as a 12n3tion. 41ter t"e 4$ . 1ollowed b t"e 12n3tionHs na5e."e 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. O2r 12n3tion "as one para5eter (t"e list o1 s3ores) t"at we na5ed xs. 9indin! t"e a0era!e li/e t"is is a 0er !eneral proble5.e5xs GH4loat>@6 4loat>@ 7 panic53Not :mplemented36 8 92n3tions start wit" t"e /e word 4unc. .e 12n3tion will need to ta/e in a sli3e o1 4loat>@s and ret2rn one 4loat>@."is pro!ra5 3o5p2tes t"e a0era!e o1 a series o1 n25bers.e xs 7 total BE v 8 4mt.+rintln5total / 4loat>@5len5xs666 8 ./ 4or M< v :E ran. (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 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."is wonHt wor/( 4unc 456 7 4mt.e5someTtherName66 8 4nd o2r pro!ra5 wo2ld still wor/. rat"er t"an tr in! to i5ple5ent t"e entire t"in! in one lar!e step.+rintln5avera. @odi1 main to loo/ li/e t"is( 4unc main56 7 xs :E GH4loat>@7A=<A?<OO<= <=?8 4mt. . 4 1ew t"in!s to /eep in 5ind( • . 9inall we "a0e t"e 12n3tion bod w"i3" is a series o1 state5ents between 32rl bra3es. 'ow lets ta/e t"e 3ode 1ro5 o2r 5ain 12n3tion and 5o0e it into o2r a0era!e 12n3tion( 4unc avera.+rintln to be a return instead. Colle3ti0el t"e para5eters and t"e ret2rn t pe are /nown as t"e 12n3tionHs si!nat2re.e5xs66 8 >2nnin! t"is pro!ra5 s"o2ld !i0e o2 exa3tl t"e sa5e res2lt as t"e ori!inal. (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. In t"is bod we in0o/e a b2ilt.para5eters we p2t t"e ret2rn t pe.e xs 7 total BE v 8 return total / 4loat>@5len5xs66 8 'oti3e t"at we 3"an!ed t"e 4mt.+rintln5avera.+rintln5x6 8 4unc main56 7 x :E " 456 8 We need to eit"er do t"is( 41 . • 92n3tions donHt "a0e a33ess to an t"in! in t"e 3allin! 12n3tion. .e5xs GH4loat>@6 4loat>@ 7 total :E /./ 4or M< v :E ran. 9or exa5ple we 3o2ld "a0e done t"is( 4unc main56 7 someTtherName :E GH4loat>@7A=<A?<OO<= <=?8 4mt.in 12n3tion 3alled panic w"i3" 3a2ses a r2n ti5e error."e na5es o1 t"e para5eters donHt "a0e to 5at3" in t"e 3allin! 12n3tion.

S2ppose we "ad t"is pro!ra5( 4unc main56 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 .4unc 45x int6 7 4mt.+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( .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/.+rintln5x6 8 4unc main56 7 456 8 • 92n3tions are b2ilt 2p in a Ista3/J.

int6 int 7 return x B 8 43 . or a boolean to indi3ate s233ess (x< o& :E 456). In t"is 3ase we ta/e 6ero or 5ore ints..int6 int 7 total :E / 4or M< v :E ran.( 4unc main56 7 xs :E GHint7$< <?8 4mt. (."ree 3"an!es are ne3essar ( 3"an!e t"e ret2rn t pe to 3ontain 52ltiple t pes separated b <..+rintln5add5$< <?66 8 & 2sin! . 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."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" ... .:E 456 ..."is is pre3isel "ow t"e 4mt.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.8 x< ..+rintln 12n3tion is i5ple5ented( 4unc +rintln5a .+rintln5add5xs.inter4ace786 5n int< err error6 ."ere is a spe3ial 1or5 a0ailable 1or t"e last para5eter in a Go 12n3tion( 4unc add5ar..66 8 Closure It is possible to 3reate 12n3tions inside o1 12n3tions( 4unc main56 7 add :E 4unc5x< .e ar. 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. @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.. !ariadi" Fun"tions .s .

9or exa5ple "ereHs "ow we 5i!"t !enerate all t"e e0en n25bers( 4unc ma&e.8 add 4mt.+rintln5increment566 8 increment adds 1 to t"e 0ariable x w"i3" is de1ined in t"e main 12n3tionHs s3ope.+rintln5increment566 4mt."is x 0ariable 3an be a33essed and 5odi1ied b t"e increment 12n3tion. 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.ven566 // / 4mt.+rintln5next."is is w" t"e 1irst ti5e we 3all increment we see 1 displa ed. In t"is 3ase increment and t"e 0ariable x 1or5 t"e 3los2re.ven :E ma&e.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.+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). 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.ven566 // @ 8 ret2rns a 12n3tion w"i3" !enerates e0en n25bers. . =ere is one wa to 3o5p2te t"e 1a3torial o1 a n25ber( 4unc 4actorial5x uint6 uint 7 44 .ven2enerator Re"ursion 9inall a 12n3tion is able to 3all itsel1.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.ven566 // 4mt.ven2enerator56 4mt. b2t t"e se3ond ti5e we 3all it we see 2 displa ed. .+rintln5next. . ma&e.+rintln5next. 4 12n3tion li/e t"is to!et"er wit" t"e non.lo3al 0ariables it re1eren3es is /nown as a 3los2re.

i4 x EE / 7 return $ 8 8 return x 9 4actorial5x#$6 3alls itsel1. lets wal/ t"ro2!" 4actorial5 6( 4actorial • • Is x EE /O 'o. w"i3" is w"at 5a/es t"is 12n3tion re32rsi0e. i1 state5ents. $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."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!.+rintln53$st36 8 4unc second56 7 4mt.e main import 34mt3 4unc 4irst56 7 4mt. &asi3all de1er 5o0es t"e 3all to second to 4- .+rintln53 nd36 8 4unc main56 7 de4er second56 4irst56 8 . In order to better 2nderstand "ow t"is 12n3tion wor/s. 0ariables and si5ple 12n3tions. (x is 2) 9ind t"e 1a3torial o1 x Y $ o o Is x EE /O 'o. Consider t"e 1ollowin! exa5ple( pac&a. ret2rn 1. @ost people will 1ind 12n3tional pro!ra55in! 5ore di11i32lt to 2nderstand t"an an approa3" based on 1or loops. (x is 1) 9ind t"e 4actorial o1 x Y $  Is x EE /O <es.

e main import 34mt3 4unc main56 7 de4er 4unc56 7 str :E recover56 4mt.Tpen54ilename6 de4er 4. 1or!ettin! to initiali6e a 5ap. 9or exa5ple w"en we open a 1ile we need to 5a/e s2re to 3lose it later.arlier we 3reated a 12n3tion t"at 3alled t"e panic 12n3tion to 3a2se a r2n ti5e error."is "as 3 ad0anta!es( (1) it /eeps o2r Close 3all near o2r Tpen 3all so its easier to 2nderstand.+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.ti5e pani3 wit" t"e b2ilt. We 3an "andle a r2n.+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.e main import 34mt3 4unc main56 7 panic53+WN:C36 str :E recover56 4mt. recover stops t"e pani3 and ret2rns t"e 0al2e t"at was passed to t"e 3all to panic.Close56 . (=en3e t"e na5e Ipani3J) 46 .8 second56 is o1ten 2sed w"en reso2r3es need to be 1reed in so5e wa . et3. Instead we "a0e to pair it wit" de4er( pac&a.in recover 12n3tion.ti5e pani3 o332rs.) or an ex3eptional 3ondition t"at t"ereHs no eas wa to re3o0er 1ro5. We 5i!"t be te5pted to 2se it li/e t"is( pac&a. Wit" de4er( de4er 4< M :E os. Pani" & 'e"o(er . (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.

Write a re32rsi0e 12n3tion w"i3" 3an 1ind 4ib5n6. pani3 and re3o0erO =ow do o2 re3o0er 1ro5 a r2n. write a ma&eTdd2enerator 12n3tion t"at !enerates odd n25bers. sum • Write a 12n3tion wit" one 0ariadi3 para5eter t"at 1inds t"e !reatest n25ber in a list o1 n25bers. . 9or exa5ple hal45$6 s"o2ld ret2rn 5/< 4alse6 and hal45 6 s"o2ld ret2rn 5$< true6.ven2enerator as an exa5ple. Esin! ma&e.Problems • • is a 12n3tion w"i3" ta/es a sli3e o1 n25bers and adds t"e5 to!et"er. 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.ti5e pani3O • • • 4* ."e 9ibona33i seF2en3e is de1ined as( 4ib5/6 E /. W"at are de1er. 4ib5n6 E 4ib5n#$6 B 4ib5n# 6. 4ib5$6 E $.

In t"e Zero 12n3tion x+tr is a pointer to an int. Ix in main and x+tr in Zero re1er to t"e sa5e 5e5or lo3ation.+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 ret2rns a 9int (pointer to an int) be3a2se x is an int.+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. is also 2sed to Idere1eren3eJ pointer 0ariables. w"i3" 3an onl be !i0en anot"er 9int."is is w"at allows 2s to 5odi1 t"e ori!inal 0ariable. I1 we tr x+tr E / instead we will !et a 3o5piler error be3a2se x+tr is not an int itHs a 9int. 9 9inall we 2se t"e I operator to 1ind t"e address o1 a 0ariable. W"en we write 9x+tr E / we are sa in! Istore t"e int $ in t"e 5e5or lo3ation x+tr re1ers toJ. 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."e point to so5et"in! else) & 2sin! a pointer (9int) t"e Zero 12n3tion is able to 5odi1 t"e ori!inal 0ariable. &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. new 4not"er wa to !et a pointer is to 2se t"e b2ilt.in ne) 12n3tion( 4+ .Pointers W"en we 3all a 12n3tion t"at ta/es an ar!25ent. (. %ere1eren3in! a pointer !i0es 2s a33ess to t"e 0al2e t"e pointer points to. . 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.

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. 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 $. Q s)ap5Ix< 4) .in t pes. b2t as we will see in t"e next 3"apter.:E I-6 s"o2ld !i0e o2 xE and -E$)." 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.4unc one5x+tr 9int6 7 9x+tr E $ 8 4unc main56 7 x+tr :E ne)5int6 one5x+tr6 4mt. Go is not li/e t"is. t"e are extre5el 2se12l w"en paired wit" str23ts. 8ointers are rarel 2sed wit" GoHs b2ilt. wit" !reat 3are bein! needed to e0ent2all delete an t"in! 3reated wit" ne). ne) In so5e pro!ra55in! lan!2a!es t"ere is a si!ni1i3ant di11eren3e between 2sin! ne) and I. allo3ates eno2!" 5e5or to 1it a 0al2e o1 t"at t pe and ret2rns a pointer to it.

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

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

+i 9 c.. DetHs do t"e sa5e t"in! 1or t"e re3tan!le( t-pe \ectan.+rintln5circleWrea5Ic66 %ethods 4lt"o2!" t"is is better t"an t"e 1irst 0ersion o1 t"is 3ode.x$< r.-$6 return l 9 ) 8 main "as( r :E \ectan. operator( 4mt.a relations"ip. 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.c :E Circle7/< /< "8 4mt.x$< r.r9c. 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.le7/< /< $/< $/8 4mt.+rintln530i< m.x < r."is is 523" easier to read. .le struct 7 x$< -$< x < .area566 .4loat>@ 8 4unc 5r 9\ectan. S2ppose we "ad a person str23t( t-pe +erson struct 7 Name strin.-$< r.6 ) :E distance5r. 9or exa5ple a Circle "as a radius.x$< r.Name6 8 4nd we wanted to 3reate a new Wndroid str23t."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 .+rintln5c.+rintln5r.r 8 In between t"e /e word 4unc and t"e na5e o1 t"e 12n3tion weH0e added a Ire3ei0erJ.area566 Embedded Types 4 str23tHs 1ields 2s2all represent t"e "as. We 3o2ld do t"is( t-pe Wndroid struct 7 -2 . 8 4unc 5p 9+erson6 Ual&56 7 4mt.name is3< p.le6 area56 4loat>@ 7 l :E distance5r.-$< r.

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

shapes 7 area BE s.area56 8 return area 8 'ow a *ultiShape 3an 3ontain Circles.le.les or e0en ot"er *ultiShapes. I5ple5ent t"e 5et"od 1or Circle and \ectan.+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.e m. 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. \ectan. • -4 .8 return area 8 We wo2ld 3all t"is 12n3tion li/e t"is( 4mt.

!on"urren"y Dar!e pro!ra5s are o1ten 5ade 2p o1 5an s5aller s2b.o 45i6 8 var input strin.o 45/6. 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 . 9or exa5ple a web ser0er "andles reF2ests 5ade 1ro5 web browsers and ser0es 2p =. ."e se3ond !oro2tine is 3reated w"en we 3all .Scanln5Iinput6 8 . 4mt. 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).e main import 34mt3 4unc 45n int6 7 4or i :E /Q i R $/Q iBB 7 4mt.Scanln5Iinput6 8 -- .o 3reate a !oro2tine we 2se t"e /e word .+rintln5n< 3:3< i6 8 8 4unc main56 7 .pro!ra5s. '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.o 45/6 var input strin."is pro!ra5 3onsists o1 two !oro2tines. @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. 4mt.a3" reF2est is "andled li/e a s5all pro!ra5.@D web pa!es in response. . Wit" a !oro2tine we ret2rn i55ediatel to t"e next line and donHt wait 1or t"e 12n3tion to 3o5plete. Goroutines 4 !oro2tine is a 12n3tion t"at is 3apable o1 r2nnin! 3on32rrentl wit" ot"er 12n3tions. Go "as ri3" s2pport 1or 3on32rren3 2sin! !oro2tines and 3"annels."e 1irst !oro2tine is i5pli3it and is t"e 5ain 12n3tion itsel1.

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

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

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

+rintln53*essa.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.Second6: 4mt. 6 case R# time."e de1a2lt 3ase "appens i55ediatel i1 none o1 t"e 3"annels are read . :E R# c : 4mt. 'or5all 3"annels are s n3"rono2sU bot" sides o1 t"e 3"annel will wait 2ntil t"e ot"er side is read .+rintln53timeout36 de4ault: 4mt.3reates a 3"annel and a1ter t"e !i0en d2ration will send t"e 32rrent ti5e on it. read-36 8 .$ :E R# c$: 4mt.W4ter.$6 case ms.e $3< ms."is 3reates a b211ered 3"annel wit" a 3apa3it o1 1. -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 . W"at is a b211ered 3"annelO =ow wo2ld o2 3reate one wit" a 3apa3it o1 2$O -) .W4ter select 7 case ms.+rintln53*essa.+rintln53nothin.W4ter5time. 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. Problems • • • =ow do o2 spe3i1 t"e dire3tion o1 a 3"annel t peO Write o2r own Sleep 12n3tion 2sin! time.

It speeds 2p t"e 3o5piler b onl reF2irin! re3o5pilation o1 s5aller 3"2n/s o1 a pro!ra5.J 4s we saw in 3"apter * 12n3tions are t"e 1irst la er we t2rn to allow 3ode re2se.ages Go was desi!ned to be a lan!2a!e t"at en3o2ra!es !ood so1tware en!ineerin! pra3ti3es. 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. &2ndlin! 3ode in t"is wa ser0es 3 p2rposes( 4mt • • • It red23es t"e 3"an3e o1 "a0in! o0erlappin! na5es. we donHt "a0e to re3o5pile it e0er ti5e we 3"an!e o2r pro!ra5.e5xs GH4loat>@6 4loat>@ 7 total :E 4loat>@5/6 4or M< x :E ran.+rintln5av. Inside t"at 1older 3reate a 1ile 3alled main. Create a 1older in '/2o/src/. 4lt"o2!" we 2se t"e pa3/a!e 4mt. Wit"o2t t"is separate pro!ra5 we "a0e no wa o1 2sin! t"e pa3/a!e we 3reate.e xs 7 total BE x 6$ . :E 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. 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. Go also pro0ides anot"er 5e3"anis5 1or 3ode re2se( pa3/a!es.e math 4unc Wvera.6 8 'ow 3reate anot"er 1older inside o1 t"e chapter$$ 1older 3alled math.o w"i3" 3ontains t"is( pac&a.#boo& 3alled chapter$$.o t"at 3ontains t"is( pac&a.olan.Wvera.e5xs6 4mt.e main import 34mt3 import 3.olan. 4n i5portant part o1 "i!" F2alit so1tware is 3ode re2se G e5bodied in t"e prin3iple I%onHt >epeat <o2rsel1.Pa". .#boo&/chapter$$/math3 4unc main56 7 xs :E GH4loat>@7$< <?<@8 av."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.

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

e 0s avera./ <o2 s"o2ld be able to browse t"ro2!" all o1 t"e pa3/a!es installed on o2r s ste5."is do325entation is also a0ailable in web 1or5 b r2nnin! t"is 3o55and( .e <o2 s"o2ld see in1or5ation displa ed 1or t"e 12n3tion we N2st wrote.r2n t"e .odoc .e5xs GH4loat>@6 4loat>@ 7 I1 o2 r2n . We 3an i5pro0e t"is do325entation b addin! a 3o55ent be1ore t"e 12n3tion( // !inds the avera.odoc #httpE3:>/>/3 and enterin! t"is E>D into o2r browser( http://localhost:>/>//p&. Create *in and *ax 12n3tions w"i3" 1ind t"e 5ini525 and 5axi525 0al2es in a sli3e o1 4loat>@s.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. 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.olan. .odoc 3o55and o2 s"o2ld see o2r 3o55ent below t"e 12n3tion de1inition. =ow wo2ld o2 do325ent t"e 12n3tions o2 3reated in Y3O • • • 62 .#boo&/chapter$$/math Wvera.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 o4 a series o4 numbers 4unc Wvera. t"en re. In a ter5inal r2n t"is 3o55and( .o install in t"e math 1older.

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

avera.U6 7 4or M< pair :E ran.8 7 GH4loat>@7$< 8< $. b2t t"e pro3ess o1 writin!s tests o1ten re0eals 5ore abo2t a proble5 t"en o2 5a at 1irst reali6e. • 64 .avera.e5t 9testin.values< 3expected3< pair.ot3< v< 6 8 8 8 .. . We 3reate a struct to represent t"e inp2ts and o2tp2ts 1or t"e 12n3tion.e 7 t.rror5 3!or3< pair. 9or exa5ple."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).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."en we loop t"ro2!" ea3" one and r2n t"e 12n3tion.e< 3.values6 i4 v KE pair. Problems • Writin! a !ood s2ite o1 tests is not alwa s eas ." 8< 7 GH4loat>@7$<$<$<$<$<$8< $ 8< 7 GH4loat>@7#$<$8< / 8< 4unc UestWvera. .e tests 7 v :E Wvera. wit" o2r Wvera."en we 3reate a list o1 t"ese structs (pairs).e5pair..

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

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

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

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

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

e6 .ess5i< j int6 bool 7 return thisGiH.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.e 8 4unc 5this B-W.en.en56 int 7 return len5this6 8 4unc 5this B-W. We 3o2ld also sort b a!e b doin! t"is( t-pe B-W.Sort5B-Name5&ids66 4mt.ess and S)ap.W. =as" 12n3tions in Go are bro/en into two 3ate!ories( 3r pto!rap"i3 and non.:nter4ace and sorts it."e sort.+rintln5&ids6 8 .e main import 5 34mt3 3hash/crc? 3 6 *$ . =as"es are 1reF2entl 2sed in pro!ra55in! 1or e0er t"in! 1ro5 loo/in! 2p data to easil dete3tin! 3"an!es.e6 ."e non. .e R thisGjH.3r pto!rap"i3.:nter4ace reF2ires 3 5et"ods( . =ereHs an exa5ple 2sin! crc? ( pac&a. We t"en de1ine t"e 3 5et"ods.3r pto!rap"i3 "as" 12n3tions 3an be 1o2nd 2nderneat" t"e "as" pa3/a!e and in3l2de adler? .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.Name R thisGjH. .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. .4unc 5this B-Name6 .e GH+erson 4unc 5this B-W."e Sort 12n3tion in sort ta/es a sort. crc>@ and 4nv. Sortin! o2r list o1 people is t"en as eas as 3astin! t"e list into o2r new t pe. .ess5i< j int6 bool 7 return thisGiH. crc? .W.en56 int 7 return len5this6 8 4unc 5this B-Name6 .

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

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

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

8

."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)

0TTP
=..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

*3

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

'P!
."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

*4

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. *-

+rintln5i< 3end36 m.oc&56 4mt.e main import 5 34mt3 3s-nc3 3time3 6 4unc main56 7 m :E ne)5s-nc. relati0el rare.Unloc&56 85i6 8 var input strin.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. =ere is an exa5ple o1 a 52tex( pac&a.*utex6 4or i :E /Q i R $/Q iBB 7 .Second6 4mt.Sleep5time. 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.. 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. sin3e t"e 5a depend on a 0er spe3i1i3.raditional 52ltit"readed pro!ra55in! is di11i32ltU itHs eas to 5a/e 5ista/es and t"ose 5ista/es are "ard to 1ind.%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. 4mt. . *6 .+rintln5i< 3start36 time. and di11i32lt to reprod23e set o1 3ir325stan3es.ato5i3 operations.o 4unc5i int6 7 m.

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

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