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

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

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

We 2se /e boards. . and so be1ore we write a pro!ra5 in Go we need to "a0e a r2di5entar 2nderstandin! o1 "ow a ter5inal wor/s.The Terminal @ost o1 t"e intera3tions we "a0e wit" 3o5p2ters toda are t"ro2!" sop"isti3ated !rap"i3al 2ser inter1a3es (GEIs). 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. t pin! cmd. 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 "ad a 3on0ersation wit" t"e 3o5p2ter.exe and "ittin! enter."e Go pro!ra55in! lan!2a!e is no di11erent.

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

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

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

ext Wran!ler text editor( Di/e S3ite on Windows . 9iles 3an be opened b !oin! to 9ile L Open. =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$ • • • . 9iles 3an be sa0ed b !oin! to 9ile L Sa0e or 9ile L Sa0e 4s.nd) to sele3t text wit"o2t 2sin! t"e 5o2se Ctrl K 9 G brin!s 2p a 1ind in 1ile dialo! t"at o2 3an 2se to sear3" t"e 3ontents o1 a 1ile • OSX 9or OSX t"e installer installs t"e .• =old down s"i1t w"ile 2sin! t"e arrow /e s (or =o5e and .ext Wran!ler 3ontains a lar!e w"ite area w"ere text is entered.

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

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

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

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

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

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

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

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

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. (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) . 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 .o true 4alse true true 4alse We 2s2all 2se tr2t" tables to de1ine "ow t"ese operators wor/( .1 P ) and 1$2.1 P ))) 4lt"o2!" o0erpowered 1or t"e tas/ o2 3an 2se Go as a 3al32lator.xpression ?al2e Ttr2e 1alse T1alse tr2e .xpression ?al2e tr2e SS tr2e tr2e tr2e SS 1alse tr2e 1alse SS tr2e tr2e 1alse SS 1alse 1alse . 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).."ese are t"e si5plest t pes in3l2ded wit" Go and 1or5 t"e 1o2ndation 1ro5 w"i3" all later t pes are b2ilt.>2nnin! t"is pro!ra5 s"o2ld !i0e o2( ( .

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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. 1ollowed b t"e 12n3tionHs na5e. Insert t"is be1ore t"e main 12n3tion( 4unc avera."e avera."is pro!ra5 3o5p2tes t"e a0era!e o1 a series o1 n25bers.e 12n3tion will need to ta/e in a sli3e o1 4loat>@s and ret2rn one 4loat>@. so its an ideal 3andidate 1or de1inition as a 12n3tion.e xs 7 total BE v 8 4mt. 9indin! t"e a0era!e li/e t"is is a 0er !eneral proble5. .Fun"tions 4 12n3tion is an independent se3tion o1 3ode t"at 5aps 6ero or 5ore inp2t para5eters to 6ero or 5ore o2tp2t para5eters. O2r 12n3tion "as one para5eter (t"e list o1 s3ores) t"at we na5ed xs. . (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 para5eters (inp2ts) o1 t"e 12n3tion are de1ined li/e t"is( name t-pe< name t-pe< X./ 4or M< v :E ran.e5xs GH4loat>@6 4loat>@ 7 panic53Not :mplemented36 8 92n3tions start wit" t"e /e word 4unc. 41ter t"e 4$ .+rintln5total / 4loat>@5len5xs666 8 .

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

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

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

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

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

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

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

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

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

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

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

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

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

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.+rintln5totalWrea5Ic< Ir66 Inter1a3es 3an also be 2sed as 1ields( t-pe *ultiShape struct 7 shapes GHShape 8 We 3an e0en t2rn *ultiShape itsel1 into a Shape b !i0in! it an area 5et"od( 4unc 5m 9*ultiShape6 area56 4loat>@ 7 var area 4loat>@ 4or M< s :E ran.les or e0en ot"er *ultiShapes.8 return area 8 We wo2ld 3all t"is 12n3tion li/e t"is( 4mt. I5ple5ent t"e 5et"od 1or Circle and \ectan.shapes 7 area BE s.le.e m.area56 8 return area 8 'ow a *ultiShape 3an 3ontain Circles. • -4 . \ectan.

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

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

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

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

W"at is a b211ered 3"annelO =ow wo2ld o2 3reate one wit" a 3apa3it o1 2$O -) .W4ter5time.W4ter. Problems • • • =ow do o2 spe3i1 t"e dire3tion o1 a 3"annel t peO Write o2r own Sleep 12n3tion 2sin! time.+rintln53timeout36 de4ault: 4mt.W4ter select 7 case ms.Second6: 4mt. :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 ."e de1a2lt 3ase "appens i55ediatel i1 none o1 t"e 3"annels are read .e $3< ms. 6 case R# time. read-36 8 . 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.e 3< ms.3reates a 3"annel and a1ter t"e !i0en d2ration will send t"e 32rrent ti5e on it. -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 ."is 3reates a b211ered 3"annel wit" a 3apa3it o1 1.+rintln53*essa.+rintln53*essa.$ :E R# c$: 4mt.+rintln53nothin.$6 case ms. (we werenHt interested in t"e ti5e so we didnHt store it in a 0ariable) We 3an also spe3i1 a de4ault 3ase( time.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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.+rintln5i< 3start36 time.oc&56 4mt. .*utex6 4or i :E /Q i R $/Q iBB 7 . 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. =ere is an exa5ple o1 a 52tex( pac&a.Second6 4mt.e main import 5 34mt3 3s-nc3 3time3 6 4unc main56 7 m :E ne)5s-nc. 4mt.Unloc&56 85i6 8 var input strin.+rintln5i< 3end36 m. 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.ato5i3 operations. *6 .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.o 4unc5i int6 7 m.. and di11i32lt to reprod23e set o1 3ir325stan3es. relati0el rare.Sleep5time.%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.

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

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