Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
164 views

An Introduction To Programming in Go

This document provides an overview of the basic tools and concepts needed to get started programming in Go, including installing Go and a text editor, understanding files and folders, using the terminal, and text editors.

Uploaded by

g_teodorescu
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
164 views

An Introduction To Programming in Go

This document provides an overview of the basic tools and concepts needed to get started programming in Go, including installing Go and a text editor, understanding files and folders, using the terminal, and text editors.

Uploaded by

g_teodorescu
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 78

Installers

Installs Go and a text editor.

Windows OSX (32 bit, 64 bit)

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

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

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

Getting Started
Co5p2ter pro!ra55in! is t"e art, 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. Go is a !eneral p2rpose pro!ra55in! lan!2a!e wit" ad0an3ed 1eat2res and a 3lean s ntax. &e3a2se o1 its wide a0ailabilit on a 0ariet o1 plat1or5s, its rob2st well, do325ented 3o55on librar , and its 1o32s on !ood so1tware en!ineerin! prin3iples, Go is an ideal lan!2a!e to learn as o2r 1irst pro!ra55in! lan!2a!e. ."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. &2t be1ore we write o2r 1irst pro!ra5 in Go t"ere are a 1ew prereF2isite 3on3epts we need to 2nderstand.

Files and Folders


4 1ile is a 3olle3tion o1 data stored as a 2nit wit" a na5e. @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. 4ll 1iles are stored in t"e sa5e wa on a 3o5p2ter( t"e all "a0e a na5e, a de1inite si6e (5eas2red in b tes) and an asso3iated t pe. . 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 .. 9or exa5ple a 1ile wit" t"e na5e hello.txt "as t"e extension txt w"i3" is 2sed to represent text2al data. 9olders (also 3alled dire3tories) are 2sed to !ro2p 1iles to!et"er. ."e 3an also 3ontain ot"er 1olders. On Windows 1ile and 1older pat"s (lo3ations) are represented wit" t"e \ (ba3/slas") 3"ara3ter, 1or exa5ple( C:\Users\john\example.txt. example.txt is t"e 1ile na5e, it is 3ontained in t"e 1older john, 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). On OSX (and 5ost ot"er operatin! s ste5s) 1ile and 1older pat"s are represented wit" t"e / (1orward slas") 3"ara3ter, 1or exa5ple( /Users/john/example.txt. Di/e on Windows example.txt is t"e 1ile na5e, it is 4

3ontained in t"e 1older john, w"i3" is in t"e 1older Users. Enli/e Windows, OSX does not spe3i1 a dri0e letter w"ere t"e 1ile is stored.

Windows
On Windows 1iles and 1olders 3an be browsed 2sin! Windows ;xplorer (a33essible b do2ble,3li3/in! I@ Co5p2terJ or t pin! winKe)(

OSX
On OSX 1iles and 1olders 3an be browsed 2sin! 9inder (a33essible b 3li3/in! t"e 9inder i3on G t"e 1a3e i3on in t"e lower le1t bar)(

The Terminal
@ost o1 t"e intera3tions we "a0e wit" 3o5p2ters toda are t"ro2!" sop"isti3ated !rap"i3al 2ser inter1a3es (GEIs). We 2se /e boards, 5i3e and to23"s3reens to intera3t wit" 0is2al b2ttons or ot"er t pes o1 3ontrols t"at are displa ed on a s3reen. It wasnHt alwa s t"is wa . &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. We "ad a 3on0ersation wit" t"e 3o5p2ter. 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, 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. ."e Go pro!ra55in! lan!2a!e is no di11erent, and so be1ore we write a pro!ra5 in Go we need to "a0e a r2di5entar 2nderstandin! o1 "ow a ter5inal wor/s.

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), t pin! cmd.exe and "ittin! enter. <o2 s"o2ld see a bla3/ window appear t"at loo/s li/e t"is(

& 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. .r enterin! t"e 3o55and dir, w"i3" lists t"e 3ontents o1 a dire3tor . <o2 s"o2ld see so5et"in! li/e t"is(
C:\Users\caleb>dir Volume in drive C has no label. Volume Serial Number is B !"#!$ "

9ollowed b a list o1 t"e 1iles and 1olders 3ontained in o2r "o5e dire3tor . <o2 3an 3"an!e dire3tories b 2sin! t"e 3o55and cd. 9or exa5ple o2 probabl "a0e a 1older 3alled %es&top. <o2 3an see its 3ontents b enterin! cd %es&top and t"en enterin! dir. .o !o ba3/ to o2r "o5e dire3tor o2 3an 2se t"e spe3ial dire3tor na5e .. (two periods next to ea3" ot"er)( cd ... 4 sin!le period represents t"e 32rrent 1older (/nown as t"e wor/in! 1older), so cd . doesnHt do an t"in!. ."ere are a lot 5ore 3o55ands o2 3an 2se, b2t t"is s"o2ld be eno2!" to !et o2 started.

OSX
In OSX t"e ter5inal 3an be rea3"ed b !oin! to 9inder L 4ppli3ations L Etilities L .er5inal. <o2 s"o2ld see a window li/e t"is(

& de1a2lt t"e ter5inal starts in o2r "o5e dire3tor . (In 5 3ase t"is is /Users/caleb) <o2 iss2e 3o55ands b t pin! t"e5 in and "ittin! enter. .r enterin! t"e 3o55and ls, w"i3" lists t"e 3ontents o1 a dire3tor . <o2 s"o2ld see so5et"in! li/e t"is(
caleb#min:' caleb( ls %es&top %o)nloads %ocuments ,ibrar*ovies *usic +ictures +ublic

."ese are t"e 1iles and 1olders 3ontained in o2r "o5e dire3tor (in t"is 3ase t"ere are no 1iles). <o2 3an 3"an!e dire3tories 2sin! t"e cd 3o55and. 9or exa5ple o2 probabl "a0e a 1older 3alled %es&top. <o2 3an see its 3ontents b enterin! cd %es&top and t"en enterin! ls. .o !o ba3/ to o2r "o5e dire3tor o2 3an 2se t"e spe3ial dire3tor na5e .. (two periods next to ea3" ot"er)( cd ... 4 sin!le period represents t"e 32rrent 1older (/nown as t"e wor/in! 1older), so cd . doesnHt do an t"in!. ."ere are a lot 5ore 3o55ands o2 3an 2se, b2t t"is s"o2ld be eno2!" to !et o2 started.

Text Editors
."e pri5ar tool pro!ra55ers 2se to write so1tware is a text editor. .ext editors are si5ilar to word pro3essin! pro!ra5s (@i3roso1t Word, Open O11i3e, M) b2t 2nli/e s23" pro!ra5s t"e donHt do an 1or5attin!, ('o bold, itali3, M) instead t"e operate onl on plain text. &ot" OSX and Windows 3o5e wit" text editors b2t t"e are "i!"l li5ited and I re3o55end installin! a better one. .o 5a/e t"e installation o1 t"is so1tware easier an installer is a0ailable at t"e boo/Hs website( "ttp(CCwww.!olan!,boo/.3o5C. ."is installer will install t"e Go tool s2ite, set2p en0iron5ental 0ariables and install a text editor.

Windows
9or windows t"e installer will install t"e S3ite text editor. <o2 3an open it b !oin! to Start L 4ll 8ro!ra5s L Go L S3ite. <o2 s"o2ld see so5et"in! li/e t"is(

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

=old down s"i1t w"ile 2sin! t"e arrow /e s (or =o5e and ;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 .ext Wran!ler text editor(

Di/e S3ite on Windows .ext Wran!ler 3ontains a lar!e w"ite area w"ere text is entered. 9iles 3an be opened b !oin! to 9ile L Open. 9iles 3an be sa0ed b !oin! to 9ile L Sa0e or 9ile L Sa0e 4s. =ere are so5e 2se12l /e board s"ort32ts( (Co55and is t"e /e )

Co55and K S G sa0e t"e 32rrent 1ile Co55and K X G 32t t"e 32rrentl sele3ted text (re5o0e it and p2t it in o2r 3lipboard so it 3an be pasted later) Co55and K C G 3op t"e 32rrentl sele3ted text Co55and K ? G paste t"e text 32rrentl in t"e 3lipboard Ese t"e arrow /e s to na0i!ate 1$

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, w"i3" 5eans so2r3e 3ode (t"e 3ode o2 write) is translated into a lan!2a!e t"at o2r 3o5p2ter 3an 2nderstand. ."ere1ore be1ore we 3an write a Go pro!ra5, we need t"e Go 3o5piler. ."e installer will set2p Go 1or o2 a2to5ati3all . We will be 2sin! 0ersion 1 o1 t"e lan!2a!e. (@ore in1or5ation 3an be 1o2nd at "ttp(CCwww.!olan!.or!) DetHs 5a/e s2re e0er t"in! is wor/in!. Open 2p a ter5inal and t pe t"e 1ollowin!(
.o version

<o2 s"o2ld see t"e 1ollowin!(


.o version .o$./.

<o2r 0ersion n25ber 5a be sli!"tl di11erent. I1 o2 !et an error abo2t t"e 3o55and not bein! re3o!ni6ed tr restartin! o2r 3o5p2ter. ."e Go tool s2ite is 5ade 2p o1 se0eral di11erent 3o55ands and s2b,3o55ands. 4 list o1 t"ose 3o55ands is a0ailable b t pin!(
.o help

We will see "ow t"e are 2sed in s2bseF2ent 3"apters.

11

Your First Program


.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. DetHs write one 2sin! Go. 9irst 3reate a new 1older w"ere we 3an store o2r pro!ra5. ."e installer o2 2sed in 3"apter 1 3reated a 1older in o2r "o5e dire3tor na5ed 2o. Create a 1older na5ed '/2o/src/.olan.#boo&/chapter . (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/.olan.#boo& m&dir 2o/src/.olan.#boo&/chapter

Esin! o2r text editor t pe in t"e 1ollowin!(


pac&a.e main import 34mt3 // this is a comment 4unc main56 7 4mt.+rintln530ello 1orld36 8

@a/e s2re o2r 1ile is identi3al to w"at is s"own "ere and sa0e it as main..o in t"e 1older we N2st 3reated. Open 2p a new ter5inal and t pe in t"e 1ollowin!(
cd 2o/src/.olan.#boo&/chapter .o run main..o

<o2 s"o2ld see 0ello 1orld displa ed in o2r ter5inal. ."e .o run 3o55and ta/es t"e s2bseF2ent 1iles (separated b spa3es), 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. ."e Go 3o5piler will !i0e o2 "ints abo2t w"ere t"e 5ista/e lies. Di/e 5ost 3o5pilers, t"e Go 3o5piler is extre5el pedanti3 and "as no toleran3e 1or 5ista/es.

How to Read a Go Program


DetHs loo/ at t"is pro!ra5 in 5ore detail. Go pro!ra5s are read top to botto5, le1t to ri!"t. (li/e a boo/) ."e 1irst line sa s t"is(
pac&a.e main

."is is /nown as a Ipa3/a!e de3larationJ. ;0er Go pro!ra5 52st start wit" a pa3/a!e de3laration. 8a3/a!es are GoHs wa o1 or!ani6in! and re2sin! 3ode. ."ere are two t pes o1 Go pro!ra5s( exe32tables and libraries. ;xe32table appli3ations are t"e /inds o1 pro!ra5s t"at we 3an r2n dire3tl 1ro5 t"e ter5inal. (in Windows t"e end

12

wit" .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. We will explore libraries in 5ore detail later, 1or now N2st 5a/e s2re to in3l2de t"is line in an pro!ra5 o2 write. ."e next line is a blan/ line. Co5p2ters represent newlines wit" a spe3ial 3"ara3ter (or se0eral 3"ara3ters). 'ewlines, spa3es and tabs are /nown as w"itespa3e (be3a2se o2 3anHt see t"e5). Go 5ostl doesnHt 3are abo2t w"itespa3e, 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 ) ."en we see t"is(
import 34mt3

."e import /e word is "ow we in3l2de 3ode 1ro5 ot"er pa3/a!es to 2se wit" o2r pro!ra5. ."e 4mt pa3/a!e (s"ort"and 1or 1or5at) i5ple5ents 1or5attin! 1or inp2t and o2tp2t. Gi0en w"at we N2st learned abo2t pa3/a!es w"at do o2 t"in/ t"e 4mt pa3/a!eHs 1iles wo2ld 3ontain at t"e top o1 t"e5O 'oti3e t"at 4mt abo0e is s2rro2nded b do2ble F2otes. ."e 2se o1 do2ble F2otes li/e t"is is /nown as a Istrin! literalJ w"i3" is a t pe o1 IexpressionJ. In Go strin!s represent a seF2en3e o1 3"ara3ters (letters, n25bers, s 5bols, M) o1 a de1inite len!t". Strin!s are des3ribed in 5ore detail in t"e next 3"apter, 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!. (."e 3 3"ara3ter itsel1 is not part o1 t"e strin!) ."e line t"at starts wit" // is /nown as a 3o55ent. 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). 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. (4nd 5a in3l2de 52ltiple lines) 41ter t"is o2 see a 12n3tion de3laration(
4unc main56 7 4mt.+rintln530ello 1orld36 8

92n3tions are t"e b2ildin! blo3/s o1 a Go pro!ra5. ."e "a0e inp2ts, o2tp2ts and a series o1 steps 3alled state5ents w"i3" are exe32ted in order. 4ll 12n3tions start wit" t"e /e word 4unc 1ollowed b t"e na5e o1 t"e 12n3tion (main in t"is 3ase), a list o1 6ero or 5ore Ipara5etersJ s2rro2nded b parent"eses, an optional ret2rn t pe and a Ibod J w"i3" is s2rro2nded b 32rl bra3es. ."is 12n3tion "as no para5eters, doesnHt ret2rn an t"in! and "as onl one state5ent. ."e na5e main is spe3ial be3a2se itHs t"e 12n3tion t"at !ets 3alled w"en o2 exe32te t"e pro!ra5. ."e 1inal pie3e o1 o2r pro!ra5 is t"is line(

13

4mt.+rintln530ello 1orld36

."is state5ent is 5ade o1 t"ree 3o5ponents. 9irst we a33ess anot"er 12n3tion inside o1 t"e 4mt pa3/a!e 3alled +rintln (t"atHs t"e 4mt.+rintln pie3e, +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. 4t t"is point weH0e alread seen a lot o1 new ter5inolo! and o2 5a be a bit o0erw"el5ed. So5eti5es its "elp12l to deliberatel read o2r pro!ra5 o2t lo2d. One readin! o1 t"e pro!ra5 we N2st wrote 5i!"t !o li/e t"is( Create a new exe32table pro!ra5, w"i3" re1eren3es t"e 4mt librar and 3ontains one 12n3tion 3alled main. ."at 12n3tion ta/es no ar!25ents, 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. ."e +rintln 12n3tion does t"e real wor/ in t"is pro!ra5. <o2 3an 1ind o2t 5ore abo2t it b t pin! t"e 1ollowin! in o2r ter5inal(
.odoc 4mt +rintln

45on! ot"er t"in!s o2 s"o2ld see t"is(


+rintln 4ormats usin. the de4ault 4ormats 4or its operands and )rites to standard output. Spaces are al)a-s added bet)een operands and a ne)line is appended. :t returns the number o4 b-tes )ritten and an)rite error encountered.

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. 'e0ert"eless t"e .odoc 3o55and is extre5el 2se12l and a !ood pla3e to start w"ene0er o2 "a0e a F2estion. &a3/ to t"e 12n3tion at "and, 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. ."is 12n3tion is w"at 3a2ses 0ello 1orld to be displa ed. 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.

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.e main. W"at wo2ld t"e 1iles in t"e 4mt pa3/a!e be!in wit"O

14

We 2sed t"e +rintln 12n3tion de1ined in t"e 4mt pa3/a!e. I1 we wanted to 2se t"e ;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- name is 1ollowed b o2r na5e.

Types
In t"e last 3"apter we 2sed t"e data t pe strin! to store 0ello 1orld. %ata t pes 3ate!ori6e a set o1 related 0al2es, des3ribe t"e operations t"at 3an be done on t"e5 and de1ine t"e wa t"e are stored. 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. 8"ilosop"ers so5eti5es 5a/e a distin3tion between t pes and to/ens. 9or exa5ple s2ppose o2 "a0e a do! na5ed @ax. @ax is t"e to/en (a parti32lar instan3e or 5e5ber) and do! is t"e t pe (t"e !eneral 3on3ept). I%o!J or Ido!nessJ des3ribes a set o1 properties t"at all do!s "a0e in 3o55on. 4lt"o2!" o0ersi5plisti3 we 5i!"t reason li/e t"is( 4ll do!s "a0e 4 le!s, @ax is a do!, t"ere1ore @ax "as 4 le!s. . pes in pro!ra55in! lan!2a!es wor/ in a si5ilar wa ( 4ll strin!s "a0e a len!t", x is a strin!, t"ere1ore x "as a len!t". In 5at"e5ati3s we o1ten tal/ abo2t sets. 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. 9or exa5ple all nat2ral n25bers are asso3iati0e( I1or all nat2ral n25bers a, b, and 3, a K (b K 3) P (a K b) K 3 and a Q (b Q 3) P (a Q b) Q 3.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. Go is a stati3all t ped pro!ra55in! lan!2a!e. ."is 5eans t"at 0ariables alwa s "a0e a spe3i1i3 t pe and t"at t pe 3annot 3"an!e. Stati3 t pin! 5a see5 325berso5e at 1irst. <o2Hll spend a lar!e a5o2nt o1 o2r ti5e N2st tr in! to 1ix o2r pro!ra5 so t"at it 1inall 3o5piles. &2t t pes "elp 2s reason abo2t w"at o2r pro!ra5 is doin! and 3at3" a wide 0ariet o1 3o55on 5ista/es. Go 3o5es wit" se0eral b2ilt,in data t pes w"i3" we will now loo/ at in 5ore detail.

Numbers
Go "as se0eral di11erent t pes to represent n25bers. Generall we split n25bers into two di11erent /inds( inte!ers and 1loatin!,point n25bers.

Integers
Inte!ers G li/e t"eir 5at"e5ati3al 3o2nterpart G are n25bers wit"o2t a de3i5al 3o5ponent. (M, ,3, ,2, ,1, $, 1, M) Enli/e t"e base,1$ de3i5al s ste5 we 2se to represent n25bers, 3o5p2ters 2se a base,2 binar s ste5.

1-

O2r s ste5 is 5ade 2p o1 1$ di11erent di!its. On3e weH0e ex"a2sted o2r a0ailable di!its we represent lar!er n25bers b 2sin! 2 (t"en 3, 4, -, M) di!its p2t next to ea3" ot"er. 9or exa5ple t"e n25ber a1ter ) is 1$, t"e n25ber a1ter )) is 1$$ and so on. Co5p2ters do t"e sa5e, b2t t"e onl "a0e 2 di!its instead o1 1$. So 3o2ntin! loo/s li/e t"is( $, 1, 1$, 11, 1$$, 1$1, 11$, 111 and so on. ."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. ."e onl "a0e roo5 1or a 3ertain n25ber o1 di!its. So a 4 bit inte!er 5i!"t loo/ li/e t"is( $$$$, $$$1, $$1$, $$11, $1$$. ;0ent2all we r2n o2t o1 spa3e and 5ost 3o5p2ters N2st wrap aro2nd to t"e be!innin!. (W"i3" 3an res2lt in so5e 0er stran!e be"a0ior) GoHs inte!er t pes are( uint=, uint$>, uint? , uint>@, int=, int$>, int? and int>@. +, 16, 32 and 64 tell 2s "ow 5an bits ea3" o1 t"e t pes 2se. uint 5eans I2nsi!ned inte!erJ w"ile int 5eans Isi!ned inte!erJ. Ensi!ned inte!ers onl 3ontain positi0e n25bers (or 6ero). 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? . & tes are an extre5el 3o55on 2nit o1 5eas2re5ent 2sed on 3o5p2ters (1 b te P + bits, 1$24 b tes P 1 /ilob te, 1$24 /ilob tes P 1 5e!ab te, M) and t"ere1ore GoHs b-te data t pe is o1ten 2sed in t"e de1inition o1 ot"er t pes. ."ere are also 3 5a3"ine dependent inte!er t pes( uint, int and uintptr. ."e are 5a3"ine dependent be3a2se t"eir si6e depends on t"e t pe o1 ar3"ite3t2re o2 are 2sin!. Generall i1 o2 are wor/in! wit" inte!ers o2 s"o2ld N2st 2se t"e int t pe.

Floating Point Numbers


9loatin! point n25bers are n25bers t"at 3ontain a de3i5al 3o5ponent (real n25bers). (1.234, 123.4, $.$$$$1234, 1234$$$$) ."eir a3t2al representation on a 3o5p2ter is 1airl 3o5pli3ated and not reall ne3essar in order to /now "ow to 2se t"e5. So 1or now we need onl /eep t"e 1ollowin! in 5ind(

9loatin! point n25bers are inexa3t. O33asionall it is not possible to represent a n25ber. 9or exa5ple 3o5p2tin! $./$ # /.AA res2lts in /./ //////////////$= G 4 n25ber extre5el 3lose to w"at we wo2ld expe3t, b2t not exa3tl t"e sa5e. Di/e inte!ers 1loatin! point n25bers "a0e a 3ertain si6e (32 bit or 64 bit). Esin! a lar!er si6ed 1loatin! point n25ber in3reases itHs pre3ision. ("ow 5an di!its it 3an represent) In addition to n25bers t"ere are se0eral ot"er 0al2es w"i3" 3an be represented( Inot a n25berJ (NaN, 1or t"in!s li/e ///) and positi0e and ne!ati0e in1init . (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$ =. Generall we s"o2ld sti3/ wit" 4loat>@ w"en wor/in! wit" 1loatin! point n25bers.

16

Example
DetHs write an exa5ple pro!ra5 2sin! n25bers. 9irst 3reate a 1older 3alled chapter? and 5a/e a main..o 1ile 3ontainin! t"e 1ollowin!(
pac&a.e main import 34mt3 4unc main56 7 4mt.+rintln53$ B $ E3< $ B $6 8

I1 o2 r2n t"e pro!ra5 and o2 s"o2ld see t"is(


( .o run main..o $ B $ E

'oti3e t"at t"is pro!ra5 is 0er si5ilar to t"e pro!ra5 we wrote in 3"apter 2. It 3ontains t"e sa5e pa3/a!e line, t"e sa5e i5port line, t"e sa5e 12n3tion de3laration and 2ses t"e sa5e +rintln 12n3tion. ."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 $. ."is expression is 5ade 2p o1 t"ree parts( t"e n25eri3 literal $ (w"i3" is o1 t pe int), t"e B operator (w"i3" represents addition) and anot"er n25eri3 literal $. DetHs tr t"e sa5e t"in! 2sin! 1loatin! point n25bers(
4mt.+rintln53$ B $ E3< $./ B $./6

'oti3e t"at we 2se t"e ./ to tell Go t"at t"is is a 1loatin! point n25ber instead o1 an inte!er. >2nnin! t"is pro!ra5 will !i0e o2 t"e sa5e res2lt as be1ore. In addition to addition Go "as se0eral ot"er operators( K , 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. Go strin!s are 5ade 2p o1 indi0id2al b tes, 2s2all one 1or ea3" 3"ara3ter. (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. ."e di11eren3e between t"ese is t"at do2ble F2oted strin!s 3annot 3ontain newlines and t"e allow spe3ial es3ape seF2en3es. 9or exa5ple \n !ets repla3ed wit" a newline and \t !ets repla3ed wit" a tab 3"ara3ter.

1*

Se0eral 3o55on operations on strin!s in3l2de 1indin! t"e len!t" o1 a strin!( len530ello 1orld36, a33essin! an indi0id2al 3"ara3ter in t"e strin!( 30ello 1orld3G$H, and 3on3atenatin! two strin!s to!et"er( 30ello 3 B 31orld3. DetHs 5odi1 t"e pro!ra5 we 3reated earlier to test t"ese o2t(
pac&a.e main import 34mt3 4unc main56 7 4mt.+rintln5len530ello 1orld366 4mt.+rintln530ello 1orld3G$H6 4mt.+rintln530ello 3 B 31orld36 8

4 1ew t"in!s to noti3e(


4 spa3e is also 3onsidered a 3"ara3ter, so t"e strin!Hs len!t" is 11 not 1$ and t"e 3rd line "as 30ello 3 instead o1 30ello3. Strin!s are IindexedJ startin! at $ not 1. G$H !i0es o2 t"e 2nd ele5ent not t"e 1st. 4lso noti3e t"at o2 see $/$ instead o1 e w"en o2 r2n t"is pro!ra5. ."is is be3a2se t"e 3"ara3ter is represented b a b te (re5e5ber a b te is an inte!er). One wa to t"in/ abo2t indexin! wo2ld be to s"ow it li/e t"is instead( 30ello 1orld3$. <o2Hd read t"at as I."e strin! =ello World s2b 1,J I."e strin! =ello World at 1J or I."e se3ond 3"ara3ter o1 t"e strin! =ello WorldJ.

Con3atenation 2ses t"e sa5e s 5bol as addition. ."e Go 3o5piler 1i!2res o2t w"at to do based on t"e t pes o1 t"e ar!25ents. Sin3e bot" sides o1 t"e B are strin!s t"e 3o5piler ass25es o2 5ean 3on3atenation and not addition. (4ddition is 5eanin!less 1or strin!s)

Booleans
4 boolean 0al2e (na5ed a1ter Geor!e &oole) is a spe3ial 1 bit inte!er t pe 2sed to represent tr2e and 1alse (or on and o11). ."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.+rintln5true II 4mt.+rintln5true II 4mt.+rintln5true JJ 4mt.+rintln5true JJ 4mt.+rintln5Ktrue6 8 true6 4alse6 true6 4alse6

1+

>2nnin! t"is pro!ra5 s"o2ld !i0e o2(


( .o run main..o true 4alse true true 4alse

We 2s2all 2se tr2t" tables to de1ine "ow t"ese operators wor/( ;xpression ?al2e tr2e AA tr2e tr2e tr2e AA 1alse 1alse 1alse AA tr2e 1alse 1alse AA 1alse 1alse ;xpression ?al2e tr2e SS tr2e tr2e tr2e SS 1alse tr2e 1alse SS tr2e tr2e 1alse SS 1alse 1alse ;xpression ?al2e Ttr2e 1alse T1alse tr2e ."ese are t"e si5plest t pes in3l2ded wit" Go and 1or5 t"e 1o2ndation 1ro5 w"i3" all later t pes are b2ilt.

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 )). Gi0en t"at in binar t"e lar!est 2 di!it n25ber is 11 (3), t"e lar!est 3 di!it n25ber is 111 (*) and t"e lar!est 4 di!it n25ber is 1111 (1-) w"atHs t"e lar!est + di!it n25berO ("int( 1$1,1 P ) and 1$2,1 P ))) 4lt"o2!" o0erpowered 1or t"e tas/ o2 3an 2se Go as a 3al32lator. Write a pro!ra5 t"at 3o5p2tes ? $? " L @ @" $ and prints it to t"e ter5inal. (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)

ariables
Ep 2ntil now we "a0e onl seen pro!ra5s t"at 2se literal 0al2es (n25bers, strin!s, et3.) b2t s23" pro!ra5s arenHt parti32larl 2se12l. .o 5a/e tr2l 2se12l pro!ra5s we need to learn two new 3on3epts( 0ariables and 3ontrol 1low state5ents. ."is 3"apter will explore 0ariables in 5ore detail. 4 0ariable is a stora!e lo3ation, 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.e main import 34mt3 4unc main56 7 var x strin. E 30ello 1orld3 4mt.+rintln5x6 8

'oti3e t"at t"e strin! literal 1ro5 t"e ori!inal pro!ra5 still appears in t"is pro!ra5, b2t rat"er t"an send it dire3tl to t"e +rintln 12n3tion we assi!n it to a 0ariable instead. ?ariables in Go are 3reated b 1irst 2sin! t"e var /e word, t"en spe3i1 in! t"e 0ariable na5e (x), t"e t pe (strin.) and 1inall assi!nin! a 0al2e to t"e 0ariable (0ello 1orld). ."e last step is optional so an alternati0e wa o1 writin! t"e pro!ra5 wo2ld be li/e t"is(
pac&a.e main import 34mt3 4unc main56 7 var x strin. x E 30ello 1orld3 4mt.+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 , 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. ."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. .r r2nnin! t"e 1ollowin!(
pac&a.e main import 34mt3 4unc main56 7 var x strin. x E 34irst3

2$

4mt.+rintln5x6 x E 3second3 4mt.+rintln5x6

In 1a3t o2 3an e0en do t"is(


var x strin. x E 34irst 3 4mt.+rintln5x6 x E x B 3second3 4mt.+rintln5x6

."is pro!ra5 wo2ld be nonsense i1 o2 read it li/e an al!ebrai3 t"eore5. &2t it 5a/es sense i1 o2 are 3are12l to read t"e pro!ra5 as a list o1 3o55ands. 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.J ."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 x E x B - 1or5 is so 3o55on in pro!ra55in! t"at Go "as a spe3ial assi!n5ent state5ent( BE. We 3o2ld "a0e written x E x B 3second3 as x BE 3second3 and it wo2ld "a0e done t"e sa5e t"in!. (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. (.wo eF2al si!ns next to ea3" ot"er) EE is an operator li/e B and it ret2rns a boolean. 9or exa5ple(
var x strin. E 3hello3 var - strin. E 3)orld3 4mt.+rintln5x EE -6

."is pro!ra5 s"o2ld print 4alse be3a2se hello is not t"e sa5e as )orld. On t"e ot"er "and(
var x strin. E 3hello3 var - strin. E 3hello3 4mt.+rintln5x EE -6

."is will print true be3a2se t"e two strin!s are t"e sa5e. Sin3e 3reatin! a new 0ariable wit" a startin! 0al2e is so 3o55on Go also s2pports a s"orter state5ent(
x :E 30ello 1orld3

'oti3e t"e : be1ore t"e E and t"at no t pe was spe3i1ied. ."e t pe is not ne3essar be3a2se t"e Go 3o5piler is able to in1er t"e t pe based on t"e literal 0al2e o2 assi!n t"e 0ariable. (Sin3e o2 are assi!nin! a strin! literal, x is !i0en t"e t pe strin.) ."e 3o5piler 3an also do in1eren3e wit" t"e var state5ent(
var x E 30ello 1orld3

."e sa5e t"in! wor/s 1or ot"er t pes( 21

x :E " 4mt.+rintln5x6

Generall

o2 s"o2ld 2se t"is s"orter 1or5 w"ene0er possible.

How to Name a !ariable


'a5in! a 0ariable properl is an i5portant part o1 so1tware de0elop5ent. 'a5es 52st start wit" a letter and 5a 3ontain letters, n25bers or t"e M (2nders3ore) s 5bol. ."e Go 3o5piler doesnHt 3are w"at o2 na5e a 0ariable so t"e na5e is 5eant 1or o2r (and ot"ers) bene1it. 8i3/ na5es w"i3" 3learl des3ribe t"e 0ariableHs p2rpose. S2ppose we "ad t"e 1ollowin!(
x :E 3*ax3 4mt.+rintln53*- do.Ns name is3< x6

In t"is 3ase x is not a 0er !ood na5e 1or a 0ariable. 4 better na5e wo2ld be(
name :E 3*ax3 4mt.+rintln53*- do.Ns name is3< name6

or e0en(
do.sName :E 3*ax3 4mt.+rintln53*- do.Ns name is3< 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, b25p 3aps, 3a5el ba3/ or "25p ba3/). ."e 1irst letter o1 t"e 1irst word is lower3ase, t"e 1irst letter o1 t"e s2bseF2ent words is 2pper3ase and all t"e ot"er letters are lower3ase.

"o#e
Goin! ba3/ to t"e pro!ra5 we saw at t"e be!innin! o1 t"e 3"apter(
pac&a.e main import 34mt3 4unc main56 7 var x strin. E 30ello 1orld3 4mt.+rintln5x6 8

4not"er wa o1 writin! t"is pro!ra5 wo2ld be li/e t"is(


pac&a.e main import 34mt3 var x strin. E 30ello 1orld3 4unc main56 7

22

4mt.+rintln5x6

'oti3e t"at we 5o0ed t"e 0ariable o2tside o1 t"e 5ain 12n3tion. ."is 5eans t"at ot"er 12n3tions 3an a33ess t"is 0ariable(
var x strin. E 30ello 1orld3 4unc main56 7 4mt.+rintln5x6 8 4unc 456 7 4mt.+rintln5x6 8

."e 4 12n3tion now "as a33ess to t"e x 0ariable. 'ow s2ppose t"at we wrote t"is instead(
4unc main56 7 var x strin. E 30ello 1orld3 4mt.+rintln5x6 8 4unc 456 7 4mt.+rintln5x6 8

I1 o2 r2n t"is pro!ra5 o2 s"o2ld see an error(


.\main..o:$$: unde4ined: x

."e 3o5piler is tellin! o2 t"at t"e x 0ariable inside o1 t"e 4 12n3tion doesnHt exist. It onl exists inside o1 t"e main 12n3tion. ."e ran!e o1 pla3es w"ere o2 are allowed to 2se x is 3alled t"e s3ope o1 t"e 0ariable. 433ordin! to t"e lan!2a!e spe3i1i3ation IGo is lexi3all s3oped 2sin! blo3/sJ. &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), b2t not o2tside o1 t"e5. S3ope 3an be a little 3on12sin! at 1irstU as we see 5ore Go exa5ples it s"o2ld be3o5e 5ore 3lear.

Constants
Go also "as s2pport 1or 3onstants. Constants are basi3all 0ariables w"ose 0al2es 3annot be 3"an!ed later. ."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.e main import 34mt3 4unc main56 7 const x strin. E 30ello 1orld3 4mt.+rintln5x6 8

23

."is(
const x strin. E 30ello 1orld3 x E 3Some other strin.3

>es2lts in a 3o5pile,ti5e error(


.\main..o:O: cannot assi.n to x

Constants are a !ood wa to re2se 3o55on 0al2es in a pro!ra5 wit"o2t writin! t"e5 o2t ea3" ti5e. 9or exa5ple +i in t"e math pa3/a!e is de1ined as a 3onstant.

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

&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.e main import 34mt3 4unc main56 7 4mt.+rint53;nter a number: 36 var input 4loat>@ 4mt.Scan453P43< Iinput6 output :E input 9 4mt.+rintln5output6 8

We 2se anot"er 12n3tion 1ro5 t"e 4mt pa3/a!e to read t"e 2ser inp2t (Scan4). Iinput will be explained in a later 3"apter, 1or now all we need to /now is t"at Scan4 1ills inp2t wit" t"e n25ber we enter.

Problems

W"at are two wa s to 3reate a new 0ariableO

24

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

2-

!ontrol Stru"tures
'ow t"at we /now "ow to 2se 0ariables itHs ti5e to start writin! so5e 2se12l pro!ra5s. 9irst letHs write a pro!ra5 t"at 3o2nts to 1$, startin! 1ro5 1, wit" ea3" n25ber on its own line. Esin! w"at weH0e learned so 1ar we 3o2ld write t"is(
pac&a.e main import 34mt3 4unc main56 7 4mt.+rintln5$6 4mt.+rintln5 6 4mt.+rintln5?6 4mt.+rintln5@6 4mt.+rintln5"6 4mt.+rintln5>6 4mt.+rintln5O6 4mt.+rintln5=6 4mt.+rintln5A6 4mt.+rintln5$/6 8

Or t"is(
pac&a.e main import 34mt3 4unc main56 7 4mt.+rintln5F$ ? @ " > O = A $/F6 8

&2t bot" o1 t"ese pro!ra5s are prett tedio2s to write. W"at we need is a wa o1 doin! so5et"in! 52ltiple ti5es.

For
."e 4or state5ent allows 2s to repeat a list o1 state5ents (a blo3/) 52ltiple ti5es. >ewritin! o2r pre0io2s pro!ra5 2sin! a 4or state5ent loo/s li/e t"is(
pac&a.e main import 34mt3 4unc main56 7 i :E $

26

4or i RE $/ 7 4mt.+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. ."en we 3reate a 4or loop b 2sin! t"e /e word 4or, pro0idin! a 3onditional expression w"i3" is eit"er true or 4alse and 1inall s2ppl in! a blo3/ to exe32te. ."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). I1 t"is e0al2ates to tr2e t"en we r2n t"e state5ents inside o1 t"e blo3/. Ot"erwise we N25p to t"e next line o1 o2r pro!ra5 a1ter t"e blo3/. (in t"is 3ase t"ere is not"in! a1ter t"e 1or loop so we exit t"e pro!ra5) 41ter we r2n t"e state5ents inside o1 t"e blo3/ we loop ba3/ to t"e be!innin! o1 t"e 1or state5ent and repeat step 1.

."e i E i B $ line is extre5el i5portant, be3a2se wit"o2t it i RE $/ wo2ld alwa s e0al2ate to true and o2r pro!ra5 wo2ld ne0er stop. (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. 8rint i Set i to i B $ (i now eF2als 2) Is i RE $/O <es. 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. 'ot"in! le1t to do, so exit

Ot"er pro!ra55in! lan!2a!es "a0e a lot o1 di11erent t pes o1 loops (w"ile, do, 2ntil, 1orea3", M) b2t Go onl "as one t"at 3an be 2sed in a 0ariet o1 di11erent wa s. ."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*

8 8

4mt.+rintln5i6

'ow t"e 3onditional expression also 3ontains two ot"er state5ents wit" se5i3olons between t"e5. 9irst we "a0e t"e 0ariable initiali6ation, t"en we "a0e t"e 3ondition to 3"e3/ ea3" ti5e and 1inall we Iin3re5entJ t"e 0ariable. (addin! 1 to a 0ariable is so 3o55on t"at we "a0e a spe3ial operator( BB. Si5ilarl s2btra3tin! 1 3an be done wit" ##) We will see additional wa s o1 2sin! t"e 1or loop in later 3"apters.

If
DetHs 5odi1 t"e pro!ra5 we N2st wrote so t"at instead o1 N2st printin! t"e n25bers 1, 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. 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, ot"erwise itHs odd. So "ow do we 1ind t"e re5ainder a1ter di0ision in GoO We 2se t"e P operator. $ P eF2als $, P eF2als /, ? P eF2als $ and so on. '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/. I1 state5ents also "a0e an optional else part. I1 t"e 3ondition e0al2ates to true t"en t"e blo3/ a1ter t"e 3ondition is r2n, ot"erwise eit"er t"e blo3/ is s/ipped or i1 t"e else blo3/ is present t"at blo3/ is r2n. I1 state5ents 3an also "a0e else i4 parts(
i4 i P EE / 7 // divisible b8 else i4 i P ? EE / 7 // divisible b- ?

2+

8 else i4 i P @ EE / 7 // divisible b- @ 8

."e 3onditions are 3"e3/ed top down and t"e 1irst one to res2lt in tr2e will "a0e its asso3iated blo3/ exe32ted. 'one o1 t"e ot"er blo3/s will exe32te, e0en i1 t"eir 3onditions also pass. (So 1or exa5ple t"e n25ber + is di0isible b bot" 4 and 2, b2t t"e // divisible b- @ 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.+rintln5i< 3even36 8 else 7 4mt.+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/

."e re5ainder operator, w"ile rarel seen o2tside o1 ele5entar s3"ool, t2rns o2t to be reall 2se12l w"en pro!ra55in!. <o2Hll see it t2rn 2p e0er w"ere 1ro5 6ebra stripin! tables to partitionin! data sets.

wit"h
S2ppose we wanted to write a pro!ra5 t"at printed t"e ;n!lis" na5es 1or n25bers. Esin! w"at weH0e learned so 1ar we 5i!"t start b doin! t"is(
i4 i EE / 7 4mt.+rintln53Sero36

2)

8 else i4 i EE $ 7 4mt.+rintln53Tne36 8 else i4 i EE 7 4mt.+rintln53U)o36 8 else i4 i EE ? 7 4mt.+rintln53Uhree36 8 else i4 i EE @ 7 4mt.+rintln53!our36 8 else i4 i EE " 7 4mt.+rintln53!ive36 8

Sin3e writin! a pro!ra5 in t"is wa wo2ld be prett tedio2s Go pro0ides anot"er state5ent to 5a/e t"is easier( t"e s)itch state5ent. We 3an rewrite o2r pro!ra5 to loo/ li/e t"is(
s)itch i 7 case /: 4mt.+rintln53Sero36 case $: 4mt.+rintln53Tne36 case : 4mt.+rintln53U)o36 case ?: 4mt.+rintln53Uhree36 case @: 4mt.+rintln53!our36 case ": 4mt.+rintln53!ive36 de4ault: 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. ."e 0al2e o1 t"e expression is 3o5pared to t"e expression 1ollowin! ea3" case /e word. I1 t"e are eF2i0alent t"en t"e state5ent(s) 1ollowin! t"e : is exe32ted. Di/e an i1 state5ent ea3" 3ase is 3"e3/ed top down and t"e 1irst one to s233eed is 3"osen. 4 swit3" also s2pports a de1a2lt 3ase w"i3" will "appen i1 none o1 t"e 3ases 5at3"es t"e 0al2e. (7ind o1 li/e t"e else in an i1 state5ent) ."ese are t"e 5ain 3ontrol 1low state5ents. 4dditional state5ents will be explored in later 3"apters.

Problems

W"at does t"e 1ollowin! pro!ra5 print(


i :E $/ i4 i > $/ 7 4mt.+rintln53Bi.36 8 else 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, 6, ), et3.) Write a pro!ra5 t"at prints t"e n25bers 1ro5 1 to 1$$. &2t 1or 52ltiples o1 t"ree print W9i66W instead o1 t"e n25ber and 1or t"e 52ltiples o1 1i0e print

3$

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

31

#rrays$ Sli"es and %aps


In 3"apter 3 we learned abo2t GoHs basi3 t pes. In t"is 3"apter we will loo/ at t"ree 5ore b2ilt,in t pes( arra s, sli3es and 5aps.

&rra's
4n arra is a n25bered seF2en3e o1 ele5ents o1 a sin!le t pe wit" a 1ixed len!t". In Go t"e loo/ li/e t"is(
var x G"Hint

is an exa5ple o1 an arra w"i3" is 3o5posed o1 - ints. .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.+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. 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, arra s

are indexed startin! 1ro5 $. 4rra s are a33essed in a si5ilar wa . We 3o2ld 3"an!e 4mt.+rintln5x6 to 4mt.+rintln5xG@H6 and we wo2ld !et 1$$. =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 / "6

32

."is pro!ra5 3o5p2tes t"e a0era!e o1 a series o1 test s3ores. I1 o2 r2n it o2 s"o2ld see =>.>. DetHs wal/ t"ro2!" t"e pro!ra5(

9irst we 3reate an arra o1 len!t" - to "old o2r test s3ores, 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

."is pro!ra5 wor/s, b2t Go pro0ides so5e 1eat2res we 3an 2se to i5pro0e it. 9irst t"ese 2 parts( i R " and total / " s"o2ld t"row 2p a red 1la! 1or 2s. Sa we 3"an!ed t"e n25ber o1 !rades 1ro5 - to 6. We wo2ld also need to 3"an!e bot" o1 t"ese parts. 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.+rintln5total / len5x66

Go a"ead and 5a/e t"ese 3"an!es and r2n t"e pro!ra5. <o2 s"o2ld !et an error(
( .o run tmp..o V command#line#ar.uments .\tmp..o:$A: invalid operation: total / " 5mismatched t-pes 4loat>@ and int6

."e iss2e "ere is t"at len5x6 and total "a0e di11erent t pes. total is a 4loat>@ w"ile len5x6 is an int. So we need to 3on0ert len5x6 into a 4loat>@(
4mt.+rintln5total / 4loat>@5len5x666

."is is an exa5ple o1 a t pe 3on0ersion. In !eneral to 3on0ert between t pes o2 2se t"e t pe na5e li/e a 12n3tion. 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.e x 7 total BE value 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. We 2se t"e /e word ran.e 1ollowed b t"e na5e o1 t"e 0ariable we want to loop o0er. >2nnin! t"is pro!ra5 will res2lt in anot"er error(
( .o run tmp..o V command#line#ar.uments .\tmp..o:$>: i declared and not used

33

."e Go 3o5piler wonHt allow o2 to 3reate 0ariables t"at o2 ne0er 2se. 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.e x 7 total BE value 8 4mt.+rintln5total / 4loat>@5len5x666

4 sin!le M (2nders3ore) is 2sed to tell t"e 3o5piler t"at we donHt need t"is. (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. So5eti5es arra s li/e t"is 3an !et too lon! to 1it on one line, so Go allows o2 to brea/ it 2p li/e t"is(
x :E G"H4loat>@7 A=< A?< OO< = < =?< 8

'oti3e t"e extra trailin! < a1ter =?. ."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 . Di/e arra s sli3es are indexable and "a0e a len!t". Enli/e arra s t"is len!t" is allowed to 3"an!e. =ereHs an exa5ple o1 a sli3e(
var x GH4loat>@

."e onl di11eren3e between t"is and an arra is t"e 5issin! len!t" between t"e bra3/ets. In t"is 3ase x "as been 3reated wit" a len!t" o1 /. I1 o2 want to 3reate a sli3e o2 s"o2ld 2se t"e b2ilt,in ma&e 12n3tion(
x :E ma&e5GH4loat>@< "6

34

."is 3reates a sli3e t"at is asso3iated wit" an 2nderl in! 4loat>@ arra o1 len!t" -. Sli3es are alwa s asso3iated wit" so5e arra , and alt"o2!" t"e 3an ne0er be lon!er t"an t"e arra , t"e 3an be s5aller. ."e ma&e 12n3tion also allows a 3rd para5eter(
x :E ma&e5GH4loat>@< "< $/6

1$ represents t"e 3apa3it o1 t"e 2nderl in! arra w"i3" t"e sli3e points to(

4not"er wa to 3reate sli3es is to 2se t"e Glo) : hi.hH expression(


arr :E G"H4loat>@7$< <?<@<"8 x :E arrG/:"H

is t"e index o1 w"ere to start t"e sli3e and hi.h is t"e index w"ere to end it (b2t not in3l2din! t"e index itsel1). 9or exa5ple w"ile arrG/:"H ret2rns G$< <?<@<"H, arrG$:@H ret2rns G <?<@H.
lo)

9or 3on0enien3e we are also allowed to o5it lo), hi.h or e0en bot" lo) and hi.h. arrG/:H is t"e sa5e as arrG/:len5arr6H, arrG:"H is t"e sa5e as arrG/:"H and arrG:H is t"e sa5e as arrG/:len5arr6H.

Sli"e Fun"tions
Go in3l2des two b2ilt,in 12n3tions to assist wit" sli3es( append and cop-. =ere is an exa5ple o1 append(
4unc main56 7 slice$ :E GHint7$< <?8 slice :E append5slice$< @< "6 4mt.+rintln5slice$< slice 6 8

41ter r2nnin! t"is pro!ra5 slice$ "as G$< <?H and slice "as G$< <?<@<"H. 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. =ere is an exa5ple o1 3op (
4unc main56 7 slice$ :E GHint7$< <?8 slice :E ma&e5GHint< 6 cop-5slice < slice$6 4mt.+rintln5slice$< slice 6 8

3-

41ter r2nnin! t"is pro!ra5 slice$ "as G$< <?H and slice "as G$< H. ."e 3ontents o1 slice$ are 3opied into slice , b2t sin3e slice "as roo5 1or onl two ele5ents onl t"e 1irst two ele5ents o1 slice$ are 3opied.

%a#s
4 5ap is an 2nordered 3olle3tion o1 /e ,0al2e pairs. 4lso /nown as an asso3iati0e arra , a "as" table or a di3tionar , 5aps are 2sed to loo/ 2p a 0al2e b its asso3iated /e . =ereHs an exa5ple o1 a 5ap in Go(
var x mapGstrin.Hint

."e 5ap t pe is represented b t"e /e word map, 1ollowed b t"e /e t pe in bra3/ets and 1inall t"e 0al2e t pe. I1 o2 were to read t"is o2t lo2d o2 wo2ld sa Ix is a 5ap o1 strin.s to ints.J Di/e arra s and sli3es 5aps 3an be a33essed 2sin! bra3/ets. .r r2nnin! t"e 1ollowin! pro!ra5(
var x mapGstrin.Hint xG3&e-3H E $/ 4mt.+rintln5x6

<o2 s"o2ld see an error si5ilar to t"is(


panic: runtime error: assi.nment to entr- in nil map .oroutine $ Grunnin.H: main.main56 main..o:O B/x@d .oroutine Gs-scallH: created b- runtime.main C:/Users/W%*:N:'$/Wpp%ata/,ocal/Uemp/ /bindi t >A@AO$O//.o/src/p&./runtime/proc.c: $ exit status

Ep till now we "a0e onl seen 3o5pile,ti5e errors. ."is is an exa5ple o1 a r2nti5e error. 4s t"e na5e wo2ld i5pl , r2nti5e errors "appen w"en o2 r2n t"e pro!ra5, w"ile 3o5pile,ti5e errors "appen w"en o2 tr to 3o5pile t"e pro!ra5. ."e proble5 wit" o2r pro!ra5 is t"at 5aps "a0e to be initiali6ed be1ore t"e 3an be 2sed. We s"o2ld "a0e written t"is(
x :E ma&e5mapGstrin.Hint6 xG3&e-3H E $/ 4mt.+rintln5xG3&e-3H6

I1 o2 r2n t"is pro!ra5 o2 s"o2ld see $/ displa ed. ."e state5ent xG3&e-3H E $/ is si5ilar to w"at we saw wit" arra s b2t t"e /e , instead o1 bein! an inte!er, is a strin! be3a2se t"e 5apHs /e t pe is strin.. We 3an also 3reate 5aps wit" a /e t pe o1 int(

36

x :E ma&e5mapGintHint6 xG$H E $/ 4mt.+rintln5xG$H6

."is loo/s 0er 523" li/e an arra b2t t"ere are a 1ew di11eren3es. 9irst t"e len!t" o1 a 5ap (1o2nd b doin! len5x6) 3an 3"an!e as we add new ite5s to it. W"en 1irst 3reated it "as a len!t" o1 $, a1ter xG$H E $/ it "as a len!t" o1 1. Se3ond 5aps are not seF2ential. We "a0e xG$H, and wit" an arra t"at wo2ld i5pl t"ere 52st be an xG/H, b2t 5aps donHt "a0e t"is reF2ire5ent. We 3an also delete ite5s 1ro5 a 5ap 2sin! t"e b2ilt,in delete 12n3tion(
delete5x< $6

DetHs loo/ at an exa5ple pro!ra5 t"at 2ses a 5ap(


pac&a.e main import 34mt3 4unc main56 7 elements :E ma&e5mapGstrin.Hstrin.6 elementsG303H E 30-dro.en3 elementsG30e3H E 30elium3 elementsG3,i3H E 3,ithium3 elementsG3Be3H E 3Ber-llium3 elementsG3B3H E 3Boron3 elementsG3C3H E 3Carbon3 elementsG3N3H E 3Nitro.en3 elementsG3T3H E 3Tx-.en3 elementsG3!3H E 3!luorine3 elementsG3Ne3H E 3Neon3 4mt.+rintln5elementsG3,i3H6 8

is a 5ap t"at represents t"e 1irst 1$ 3"e5i3al ele5ents indexed b t"eir s 5bol. ."is is a 0er 3o55on wa o1 2sin! 5aps( as a loo/2p table or a di3tionar . S2ppose we tried to loo/ 2p an ele5ent t"at doesnHt exist(
elements 4mt.+rintln5elementsG3Un3H6

I1 o2 r2n t"is o2 s"o2ld see not"in! ret2rned. .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!). 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.+rintln5name< o&6

433essin! an ele5ent o1 a 5ap 3an ret2rn two 0al2es instead o1 N2st one. ."e 1irst 0al2e is t"e res2lt o1 t"e loo/2p, t"e se3ond tells 2s w"et"er or not t"e loo/2p was s233ess12l. In Go we o1ten see 3ode li/e t"is(
i4 name< o& :E elementsG3Un3HQ o& 7

3*

4mt.+rintln5name< o&6

9irst we tr to !et t"e 0al2e 1ro5 t"e 5ap, t"en i1 itHs s233ess12l we r2n t"e 3ode inside o1 t"e blo3/. Di/e we saw wit" arra s t"ere is also a s"orter wa to 3reate 5aps(
elements :E mapGstrin.Hstrin.7 303: 30-dro.en3< 30e3: 30elium3< 3,i3: 3,ithium3< 3Be3: 3Ber-llium3< 3B3: 3Boron3< 3C3: 3Carbon3< 3N3: 3Nitro.en3< 3T3: 3Tx-.en3< 3!3: 3!luorine3< 3Ne3: 3Neon3< 8

@aps are also o1ten 2sed to store !eneral in1or5ation. 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.HmapGstrin.Hstrin.7 303: mapGstrin.Hstrin.7 3name3:30-dro.en3< 3state3:3.as3< 8< 30e3: mapGstrin.Hstrin.7 3name3:30elium3< 3state3:3.as3< 8< 3,i3: mapGstrin.Hstrin.7 3name3:3,ithium3< 3state3:3solid3< 8< 3Be3: mapGstrin.Hstrin.7 3name3:3Ber-llium3< 3state3:3solid3< 8< 3B3: mapGstrin.Hstrin.7 3name3:3Boron3< 3state3:3solid3< 8< 3C3: mapGstrin.Hstrin.7 3name3:3Carbon3< 3state3:3solid3< 8< 3N3: mapGstrin.Hstrin.7 3name3:3Nitro.en3< 3state3:3.as3< 8< 3T3: mapGstrin.Hstrin.7 3name3:3Tx-.en3< 3state3:3.as3< 8<

3+

3!3:

8< 3Ne3: mapGstrin.Hstrin.7 3name3:3Neon3< 3state3:3.as3< 8< 8 i4 el< o& :E elementsG3,i3HQ o& 7 4mt.+rintln5elG3name3H< elG3state3H6 8

mapGstrin.Hstrin.7 3name3:3!luorine3< 3state3:3.as3<

'oti3e t"at t"e t pe o1 o2r 5ap "as 3"an!ed 1ro5 mapGstrin.Hstrin. to mapGstrin.HmapGstrin.Hstrin.. We now "a0e a 5ap o1 strin!s to 5aps o1 strin!s to strin!s. ."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, in 3"apter ) we will see a better wa to store str23t2red in1or5ation.

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.73a3<3b3<3c3<3d3<3e3<3438

w"at wo2ld xG :"H !i0e o2O


Write a pro!ra5 t"at 1inds t"e s5allest n25ber in t"is list(


x :E GHint7 @=<A><=><>=< "O<= <>?<O/< ?O<?@<=?< O< $A<AO< A<$O< 8

3)

Fun"tions
4 12n3tion is an independent se3tion o1 3ode t"at 5aps 6ero or 5ore inp2t para5eters to 6ero or 5ore o2tp2t para5eters. 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.

(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 /./ 4or M< v :E ran.e xs 7 total BE v 8 4mt.+rintln5total / 4loat>@5len5xs666

."is pro!ra5 3o5p2tes t"e a0era!e o1 a series o1 n25bers. 9indin! t"e a0era!e li/e t"is is a 0er !eneral proble5, so its an ideal 3andidate 1or de1inition as a 12n3tion. ."e avera.e 12n3tion will need to ta/e in a sli3e o1 4loat>@s and ret2rn one 4loat>@. Insert t"is be1ore t"e main 12n3tion(
4unc avera.e5xs GH4loat>@6 4loat>@ 7 panic53Not :mplemented36 8

92n3tions start wit" t"e /e word 4unc, 1ollowed b t"e 12n3tionHs na5e. ."e para5eters (inp2ts) o1 t"e 12n3tion are de1ined li/e t"is( name t-pe< name t-pe< X. O2r 12n3tion "as one para5eter (t"e list o1 s3ores) t"at we na5ed xs. 41ter t"e

4$

para5eters we p2t t"e ret2rn t pe. Colle3ti0el t"e para5eters and t"e ret2rn t pe are /nown as t"e 12n3tionHs si!nat2re. 9inall we "a0e t"e 12n3tion bod w"i3" is a series o1 state5ents between 32rl bra3es. In t"is bod we in0o/e a b2ilt,in 12n3tion 3alled panic w"i3" 3a2ses a r2n ti5e error. (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, rat"er t"an tr in! to i5ple5ent t"e entire t"in! in one lar!e step. 'ow lets ta/e t"e 3ode 1ro5 o2r 5ain 12n3tion and 5o0e it into o2r a0era!e 12n3tion(
4unc avera.e5xs GH4loat>@6 4loat>@ 7 total :E /./ 4or M< v :E ran.e xs 7 total BE v 8 return total / 4loat>@5len5xs66 8

'oti3e t"at we 3"an!ed t"e 4mt.+rintln to be a return instead. ."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. @odi1 main to loo/ li/e t"is(
4unc main56 7 xs :E GH4loat>@7A=<A?<OO<= <=?8 4mt.+rintln5avera.e5xs66 8

>2nnin! t"is pro!ra5 s"o2ld !i0e o2 exa3tl t"e sa5e res2lt as t"e ori!inal. 4 1ew t"in!s to /eep in 5ind(

."e na5es o1 t"e para5eters donHt "a0e to 5at3" in t"e 3allin! 12n3tion. 9or exa5ple we 3o2ld "a0e done t"is(

4unc main56 7 someTtherName :E GH4loat>@7A=<A?<OO<= <=?8 4mt.+rintln5avera.e5someTtherName66 8

4nd o2r pro!ra5 wo2ld still wor/.

92n3tions donHt "a0e a33ess to an t"in! in t"e 3allin! 12n3tion. ."is wonHt wor/(

4unc 456 7 4mt.+rintln5x6 8 4unc main56 7 x :E " 456 8

We need to eit"er do t"is(

41

4unc 45x int6 7 4mt.+rintln5x6 8 4unc main56 7 x :E " 45x6 8

Or t"is(
var x int E " 4unc 456 7 4mt.+rintln5x6 8 4unc main56 7 456 8

92n3tions are b2ilt 2p in a Ista3/J. S2ppose we "ad t"is pro!ra5(

4unc main56 7 4mt.+rintln54$566 8 4unc 4$56 int 7 return 4 56 8 4unc 4 56 int 7 return $ 8

We 3o2ld 0is2ali6e it li/e t"is(

;a3" ti5e we 3all a 12n3tion we p2s" it onto t"e 3all sta3/ and ea3" ti5e we ret2rn 1ro5 a 12n3tion we pop t"e last 12n3tion o11 o1 t"e sta3/.

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

x< - :E 456

."ree 3"an!es are ne3essar ( 3"an!e t"e ret2rn t pe to 3ontain 52ltiple t pes separated b <, 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. @2ltiple 0al2es are o1ten 2sed to ret2rn an error 0al2e alon! wit" t"e res2lt (x< err :E 456), or a boolean to indi3ate s233ess (x< o& :E 456).

!ariadi" Fun"tions
."ere is a spe3ial 1or5 a0ailable 1or t"e last para5eter in a Go 12n3tion(
4unc add5ar.s ...int6 int 7 total :E / 4or M< v :E ran.e ar.s 7 total BE v 8 return total 8 4unc main56 7 4mt.+rintln5add5$< <?66 8

& 2sin! ... 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. In t"is 3ase we ta/e 6ero or 5ore ints. We in0o/e t"e 12n3tion li/e an ot"er 12n3tion ex3ept we 3an pass as 5an ints as we want. ."is is pre3isel "ow t"e 4mt.+rintln 12n3tion is i5ple5ented(
4unc +rintln5a ...inter4ace786 5n int< err error6

."e +rintln 12n3tion ta/es an n25ber o1 0al2es o1 an t pe. (."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" ...(
4unc main56 7 xs :E GHint7$< <?8 4mt.+rintln5add5xs...66 8

Closure
It is possible to 3reate 12n3tions inside o1 12n3tions(
4unc main56 7 add :E 4unc5x< - int6 int 7 return x B 8

43

8 add

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). 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.+rintln5increment566 4mt.+rintln5increment566 8 increment adds 1 to t"e 0ariable x w"i3" is de1ined in t"e main 12n3tionHs s3ope. ."is x 0ariable 3an be a33essed and 5odi1ied b t"e increment 12n3tion. ."is is w" t"e 1irst ti5e we 3all increment we see 1 displa ed, b2t t"e se3ond ti5e we 3all it we

see 2 displa ed. 4 12n3tion li/e t"is to!et"er wit" t"e non,lo3al 0ariables it re1eren3es is /nown as a 3los2re. In t"is 3ase increment and t"e 0ariable x 1or5 t"e 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. 9or exa5ple "ereHs "ow we 5i!"t !enerate all t"e e0en n25bers(
4unc ma&e;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;ven :E ma&e;ven2enerator56 4mt.+rintln5next;ven566 // / 4mt.+rintln5next;ven566 // 4mt.+rintln5next;ven566 // @ 8

ret2rns a 12n3tion w"i3" !enerates e0en n25bers. ;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.
ma&e;ven2enerator

Re"ursion
9inall a 12n3tion is able to 3all itsel1. =ere is one wa to 3o5p2te t"e 1a3torial o1 a n25ber(
4unc 4actorial5x uint6 uint 7

44

i4 x EE / 7 return $ 8 8 return x 9 4actorial5x#$6

3alls itsel1, w"i3" is w"at 5a/es t"is 12n3tion re32rsi0e. In order to better 2nderstand "ow t"is 12n3tion wor/s, lets wal/ t"ro2!" 4actorial5 6(
4actorial

Is x EE /O 'o. (x is 2) 9ind t"e 1a3torial o1 x Y $


o o

Is x EE /O 'o. (x is 1) 9ind t"e 4actorial o1 x Y $

Is x EE /O <es, ret2rn 1.

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!. @ost people will 1ind 12n3tional pro!ra55in! 5ore di11i32lt to 2nderstand t"an an approa3" based on 1or loops, i1 state5ents, 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. Consider t"e 1ollowin! exa5ple(
pac&a.e main import 34mt3 4unc 4irst56 7 4mt.+rintln53$st36 8 4unc second56 7 4mt.+rintln53 nd36 8 4unc main56 7 de4er second56 4irst56 8

."is pro!ra5 prints $st 1ollowed b t"e end o1 t"e 12n3tion(


4unc main56 7 4irst56

nd.

&asi3all de1er 5o0es t"e 3all to second to

4-

second56

is o1ten 2sed w"en reso2r3es need to be 1reed in so5e wa . 9or exa5ple w"en we open a 1ile we need to 5a/e s2re to 3lose it later. Wit" de4er(
de4er 4< M :E os.Tpen54ilename6 de4er 4.Close56

."is "as 3 ad0anta!es( (1) it /eeps o2r Close 3all near o2r Tpen 3all so its easier to 2nderstand, (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,ti5e pani3 o332rs.

Pani" & 'e"o(er


;arlier we 3reated a 12n3tion t"at 3alled t"e panic 12n3tion to 3a2se a r2n ti5e error. We 3an "andle a r2n,ti5e pani3 wit" t"e b2ilt,in recover 12n3tion. recover stops t"e pani3 and ret2rns t"e 0al2e t"at was passed to t"e 3all to panic. We 5i!"t be te5pted to 2se it li/e t"is(
pac&a.e main import 34mt3 4unc main56 7 panic53+WN:C36 str :E recover56 4mt.+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. Instead we "a0e to pair it wit" de4er(
pac&a.e main import 34mt3 4unc main56 7 de4er 4unc56 7 str :E recover56 4mt.+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, 1or!ettin! to initiali6e a 5ap, et3.) or an ex3eptional 3ondition t"at t"ereHs no eas wa to re3o0er 1ro5. (=en3e t"e na5e Ipani3J)

46

Problems

is a 12n3tion w"i3" ta/es a sli3e o1 n25bers and adds t"e5 to!et"er. W"at wo2ld its 12n3tion si!nat2re loo/ li/e in GoO Write a 12n3tion w"i3" ta/es an inte!er and "al0es it and ret2rns tr2e i1 it was e0en or 1alse i1 it was odd. 9or exa5ple hal45$6 s"o2ld ret2rn 5/< 4alse6 and hal45 6 s"o2ld ret2rn 5$< true6.
sum

Write a 12n3tion wit" one 0ariadi3 para5eter t"at 1inds t"e !reatest n25ber in a list o1 n25bers. Esin! ma&e;ven2enerator as an exa5ple, write a ma&eTdd2enerator 12n3tion t"at !enerates odd n25bers. ."e 9ibona33i seF2en3e is de1ined as( 4ib5/6 E /, 4ib5$6 E $, 4ib5n6 E 4ib5n#$6 B 4ib5n# 6. Write a re32rsi0e 12n3tion w"i3" 3an 1ind 4ib5n6. W"at are de1er, pani3 and re3o0erO =ow do o2 re3o0er 1ro5 a r2n,ti5e pani3O

4*

Pointers
W"en we 3all a 12n3tion t"at ta/es an ar!25ent, t"at ar!25ent is 3opied to t"e 12n3tion(
4unc Zero5x int6 7 x E / 8 4unc main56 7 x :E " Zero5x6 4mt.+rintln5x6 // x is 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. &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.+rintln5x6 // x is / 8

8ointers re1eren3e a lo3ation in 5e5or w"ere a 0al2e is stored rat"er t"an t"e 0al2e itsel1. (."e point to so5et"in! else) & 2sin! a pointer (9int) t"e Zero 12n3tion is able to 5odi1 t"e ori!inal 0ariable.

The , 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. In t"e Zero 12n3tion x+tr is a pointer to an int. is also 2sed to Idere1eren3eJ pointer 0ariables. %ere1eren3in! a pointer !i0es 2s a33ess to t"e 0al2e t"e pointer points to. W"en we write 9x+tr E / we are sa in! Istore t"e int $ in t"e 5e5or lo3ation x+tr re1ers toJ. 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.
9

9inall we 2se t"e I operator to 1ind t"e address o1 a 0ariable. Ix ret2rns a 9int (pointer to an int) be3a2se x is an int. ."is is w"at allows 2s to 5odi1 t"e ori!inal 0ariable. Ix in main and x+tr in Zero re1er to t"e sa5e 5e5or lo3ation.

new
4not"er wa to !et a pointer is to 2se t"e b2ilt,in ne) 12n3tion(

4+

4unc one5x+tr 9int6 7 9x+tr E $ 8 4unc main56 7 x+tr :E ne)5int6 one5x+tr6 4mt.+rintln59x+tr6 // x is $ 8

ta/es a t pe as an ar!25ent, allo3ates eno2!" 5e5or to 1it a 0al2e o1 t"at t pe and ret2rns a pointer to it.
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). Go is not li/e t"is, 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. 8ointers are rarel 2sed wit" GoHs b2ilt,in t pes, b2t as we will see in t"e next 3"apter, t"e are extre5el 2se12l w"en paired wit" str23ts.

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 $." s[uare5Ix6 8

Write a pro!ra5 t"at 3an swap two inte!ers (x :E $Q - :E I-6 s"o2ld !i0e o2 xE and -E$).

Q s)ap5Ix<

4)

Stru"ts and Inter)a"es


4lt"o2!" it wo2ld be possible 1or 2s to write pro!ra5s onl 2sin! GoHs b2ilt,in data t pes, at so5e point it wo2ld be3o5e F2ite tedio2s. Consider a pro!ra5 t"at intera3ts wit" s"apes(
pac&a.e main import 534mt3Q 3math36 4unc distance5x$< -$< x < - 4loat>@6 4loat>@ 7 a :E x Y x$ b :E - Y -$ return math.S[rt5a9a B b9b6 8 4unc rectan.leWrea5x$< -$< x < - 4loat>@6 4loat>@ 7 l :E distance5x$< -$< x$< - 6 ) :E distance5x$< -$< x < -$6 return l 9 ) 8 4unc circleWrea5x< -< r 4loat>@6 4loat>@ 7 return math.+i 9 r9r 8 4unc main56 7 var rx$< r-$ 4loat>@ E /< / var rx < r- 4loat>@ E $/< $/ var cx< c-< cr 4loat>@ E /< /< " 4mt.+rintln5rectan.leWrea5rx$< r-$< rx < r- 66 4mt.+rintln5circleWrea5cx< c-< cr66

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.

tru"ts
4n eas wa to 5a/e t"is pro!ra5 better is to 2se a str23t. 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>@ r 4loat>@ 8

."e t-pe /e word introd23es a new t pe. ItHs 1ollowed b t"e na5e o1 t"e t pe (Circle), 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. ;a3" 1ield "as a na5e and a t pe. 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

-$

Initiali*ation
We 3an 3reate an instan3e o1 o2r new Cir3le t pe in a 0ariet o1 wa s(
var c Circle

Di/e wit" ot"er data t pes, t"is will 3reate a lo3al Cir3le 0ariable t"at is b de1a2lt set to 6ero. 9or a struct 6ero 5eans ea3" o1 t"e 1ields is set to t"eir 3orrespondin! 6ero 0al2e (/ 1or ints, /./ 1or 4loats, 33 1or strin.s, nil 1or pointers, M) We 3an also 2se t"e new 12n3tion(
c :E ne)5Circle6

."is allo3ates 5e5or 1or all t"e 1ields, sets ea3" o1 t"e5 to t"eir 6ero 0al2e and ret2rns a pointer. (9Circle) @ore o1ten we want to !i0e ea3" o1 t"e 1ields a 0al2e. 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 . operator(
4mt.+rintln5c.x< c.-< c.r6 c.x E $/ c.- E "

DetHs 5odi1 t"e circleWrea 12n3tion so t"at it 2ses a Circle(


4unc circleWrea5c Circle6 4loat>@ 7 return math.+i 9 c.r9c.r 8

In 5ain we "a0e(
c :E Circle7/< /< "8 4mt.+rintln5circleWrea5c66

One t"in! to re5e5ber is t"at ar!25ents are alwa s 3opied in Go. I1 we atte5pted to 5odi1 one o1 t"e 1ields inside o1 t"e circleWrea 12n3tion, it wo2ld not 5odi1 t"e ori!inal 0ariable. &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.r 8

4nd 3"an!e 5ain(

-1

c :E Circle7/< /< "8 4mt.+rintln5circleWrea5Ic66

%ethods
4lt"o2!" t"is is better t"an t"e 1irst 0ersion o1 t"is 3ode, 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.+i 9 c.r9c.r 8

In between t"e /e word 4unc and t"e na5e o1 t"e 12n3tion weH0e added a Ire3ei0erJ. ."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 . operator(
4mt.+rintln5c.area566

."is is 523" easier to read, 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. DetHs do t"e sa5e t"in! 1or t"e re3tan!le(
t-pe \ectan.le struct 7 x$< -$< x < - 4loat>@ 8 4unc 5r 9\ectan.le6 area56 4loat>@ 7 l :E distance5r.x$< r.-$< r.x$< r.- 6 ) :E distance5r.x$< r.-$< r.x < r.-$6 return l 9 ) 8 main

"as(

r :E \ectan.le7/< /< $/< $/8 4mt.+rintln5r.area566

Embedded Types
4 str23tHs 1ields 2s2all represent t"e "as,a relations"ip. 9or exa5ple a Circle "as a radius. S2ppose we "ad a person str23t(
t-pe +erson struct 7 Name strin. 8 4unc 5p 9+erson6 Ual&56 7 4mt.+rintln530i< m- name is3< p.Name6 8

4nd we wanted to 3reate a new Wndroid str23t. We 3o2ld do t"is(


t-pe Wndroid struct 7

-2

+erson +erson *odel strin. 8

."is wo2ld wor/, b2t we wo2ld rat"er sa an 4ndroid is a 8erson, rat"er t"an an 4ndroid "as a 8erson. Go s2pports relations"ips li/e t"is b 2sin! an e5bedded t pe. 4lso /nown as anon 5o2s 1ields, e5bedded t pes loo/ li/e t"is(
t-pe Wndroid struct 7 +erson *odel strin. 8

We 2se t"e t pe (+erson) and donHt !i0e it a na5e. W"en de1ined t"is wa t"e +erson str23t 3an be a33essed 2sin! t"e t pe na5e(
a :E ne)5Wndroid6 a.+erson.Ual&56

&2t we 3an also 3all an +erson 5et"ods dire3tl on t"e Wndroid(


a :E ne)5Wndroid6 a.Ual&56

."e is,a relations"ip wor/s t"is wa int2iti0el ( 8eople 3an tal/, an android is a person, t"ere1ore an android 3an tal/.

Interfa"es
<o2 5a "a0e noti3ed t"at we were able to na5e t"e \ectan.leHs area 5et"od t"e sa5e t"in! as t"e CircleHs area 5et"od. ."is was no a33ident. In bot" real li1e and in pro!ra55in!, relations"ips li/e t"ese are 3o55onpla3e. Go "as a wa o1 5a/in! t"ese a33idental si5ilarities expli3it t"ro2!" a t pe /nown as an Inter1a3e. =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, 1ollowed b a na5e and t"e /e word inter4ace. &2t instead o1 de1inin! 1ields, we de1ine a I5et"od setJ. 4 5et"od set is a list o1 5et"ods t"at a t pe 52st "a0e in order to Ii5ple5entJ t"e inter1a3e. In o2r 3ase bot" \ectan.le and Circle "a0e area 5et"ods w"i3" ret2rn 4loat>@s so bot" t pes i5ple5ent t"e Shape inter1a3e. & itsel1 t"is wo2ldnHt be parti32larl 2se12l, b2t we 3an 2se inter1a3e t pes as ar!25ents to 12n3tions(
4unc totalWrea5shapes ...Shape6 4loat>@ 7 var area 4loat>@ 4or M< s :E ran.e shapes 7 area BE s.area56

-3

8 return area 8

We wo2ld 3all t"is 12n3tion li/e t"is(


4mt.+rintln5totalWrea5Ic< Ir66

Inter1a3es 3an also be 2sed as 1ields(


t-pe *ultiShape struct 7 shapes GHShape 8

We 3an e0en t2rn *ultiShape itsel1 into a Shape b !i0in! it an area 5et"od(
4unc 5m 9*ultiShape6 area56 4loat>@ 7 var area 4loat>@ 4or M< s :E ran.e m.shapes 7 area BE s.area56 8 return area 8

'ow a *ultiShape 3an 3ontain Circles, \ectan.les or e0en ot"er *ultiShapes.

Problems

W"atHs t"e di11eren3e between a 5et"od and a 12n3tionO W" wo2ld o2 2se an e5bedded anon 5o2s 1ield instead o1 a nor5al na5ed 1ieldO 4dd a new 5et"od to t"e Shape inter1a3e 3alled perimeter w"i3" 3al32lates t"e peri5eter o1 a s"ape. I5ple5ent t"e 5et"od 1or Circle and \ectan.le.

-4

!on"urren"y
Dar!e pro!ra5s are o1ten 5ade 2p o1 5an s5aller s2b,pro!ra5s. 9or exa5ple a web ser0er "andles reF2ests 5ade 1ro5 web browsers and ser0es 2p =.@D web pa!es in response. ;a3" reF2est is "andled li/e a s5all pro!ra5. 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). @a/in! pro!ress on 5ore t"an one tas/ si52ltaneo2sl is /nown as 3on32rren3 . Go "as ri3" s2pport 1or 3on32rren3 2sin! !oro2tines and 3"annels.

Goroutines
4 !oro2tine is a 12n3tion t"at is 3apable o1 r2nnin! 3on32rrentl wit" ot"er 12n3tions. .o 3reate a !oro2tine we 2se t"e /e word .o 1ollowed b a 12n3tion in0o3ation(
pac&a.e main import 34mt3 4unc 45n int6 7 4or i :E /Q i R $/Q iBB 7 4mt.+rintln5n< 3:3< i6 8 8 4unc main56 7 .o 45/6 var input strin. 4mt.Scanln5Iinput6 8

."is pro!ra5 3onsists o1 two !oro2tines. ."e 1irst !oro2tine is i5pli3it and is t"e 5ain 12n3tion itsel1. ."e se3ond !oro2tine is 3reated w"en we 3all .o 45/6. '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. Wit" a !oro2tine we ret2rn i55ediatel to t"e next line and donHt wait 1or t"e 12n3tion to 3o5plete. ."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. Goro2tines are li!"twei!"t and we 3an easil 3reate t"o2sands o1 t"e5. We 3an 5odi1 o2r pro!ra5 to r2n 1$ !oro2tines b doin! t"is(
4unc main56 7 4or i :E /Q i R $/Q iBB 7 .o 45i6 8 var input strin. 4mt.Scanln5Iinput6 8

--

<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 . DetHs add so5e dela to t"e 12n3tion 2sin! time.Sleep and rand.:ntn(
pac&a.e main import 5 34mt3 3time3 3math/rand3 6 4unc 45n int6 7 4or i :E /Q i R $/Q iBB 7 4mt.+rintln5n< 3:3< i6 amt :E time.%uration5rand.:ntn5 "/66 time.Sleep5time.*illisecond 9 amt6 8 8 4unc main56 7 4or i :E /Q i R $/Q iBB 7 .o 45i6 8 var input strin. 4mt.Scanln5Iinput6 8

prints o2t t"e n25bers 1ro5 $ to 1$, waitin! between $ and 2-$ 5s a1ter ea3" one. ."e !oro2tines s"o2ld now r2n si52ltaneo2sl .
4

Channels
C"annels pro0ide a wa 1or two !oro2tines to 3o552ni3ate wit" one anot"er and s n3"roni6e t"eir exe32tion. =ere is an exa5ple pro!ra5 2sin! 3"annels(
pac&a.e main import 5 34mt3 3time3 6 4unc pin.er5c chan strin.6 7 4or i :E /Q Q iBB 7 c R# 3pin.3 8 8 4unc printer5c chan strin.6 7 4or 7 ms. :E R# c 4mt.+rintln5ms.6 time.Sleep5time.Second 9 $6 8 8 4unc main56 7 var c chan strin. E ma&e5chan strin.6

-6

.o pin.er5c6 .o printer5c6 var input strin. 4mt.Scanln5Iinput6

."is pro!ra5 will print Ipin!J 1ore0er ("it enter to stop it). 4 3"annel t pe is represented wit" t"e /e word chan 1ollowed b t"e t pe o1 t"e t"in!s t"at are passed on t"e 3"annel (in t"is 3ase we are passin! strin!s). ."e R# (le1t arrow) operator is 2sed to send and re3ei0e 5essa!es on t"e 3"annel. c R# 3pin.3 5eans send 3pin.3. ms. :E R# c 5eans re3ei0e a 5essa!e and store it in ms.. ."e 4mt line 3o2ld also "a0e been written li/e t"is( 4mt.+rintln5R#c6 in w"i3" 3ase we 3o2ld re5o0e t"e pre0io2s line. Esin! a 3"annel li/e t"is s n3"roni6es t"e two !oro2tines. W"en pin.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. (t"is is /nown as blo3/in!) DetHs add anot"er sender to t"e pro!ra5 and see w"at "appens. 4dd t"is 12n3tion(
4unc pon.er5c chan strin.6 7 4or i :E /Q Q iBB 7 c R# 3pon.3 8 8

4nd 5odi1 main(


4unc main56 7 var c chan strin. E ma&e5chan strin.6 .o pin.er5c6 .o pon.er5c6 .o printer5c6 var input strin. 4mt.Scanln5Iinput6 8

."e pro!ra5 will now ta/e t2rns printin! Ipin!J and Ipon!J.

!+annel ,ire"tion
We 3an spe3i1 a dire3tion on a 3"annel t pe t"2s restri3tin! it to eit"er sendin! or re3ei0in!. 9or exa5ple pin!erHs 12n3tion si!nat2re 3an be 3"an!ed to t"is(
4unc pin.er5c chanR# strin.6

'ow c 3an onl be sent to. 4tte5ptin! to re3ei0e 1ro5 3 will res2lt in a 3o5piler error. Si5ilarl we 3an 3"an!e printer to t"is(
4unc printer5c R#chan strin.6

-*

4 3"annel t"at doesnHt "a0e t"ese restri3tions is /nown as bi,dire3tional. 4 bi, dire3tional 3"annel 3an be passed to a 12n3tion t"at ta/es send,onl or re3ei0e,onl 3"annels, b2t t"e re0erse is not tr2e.

Sele"t
Go "as a spe3ial state5ent 3alled select w"i3" wor/s li/e a s)itch b2t 1or 3"annels(
4unc main56 7 c$ :E ma&e5chan strin.6 c :E ma&e5chan strin.6 .o 4unc56 7 4or 7 c$ R# 34rom $3 time.Sleep5time.Second 9 6 8 856 .o 4unc56 7 4or 7 c R# 34rom 3 time.Sleep5time.Second 9 ?6 8 856 .o 4unc56 7 4or 7 select 7 case ms.$ :E R# c$: 4mt.+rintln5ms.$6 case ms. :E R# c : 4mt.+rintln5ms. 6 8 8 856 var input strin. 4mt.Scanln5Iinput6

."is pro!ra5 prints I1ro5 1J e0er 2 se3onds and I1ro5 2J e0er 3 se3onds. select pi3/s t"e 1irst 3"annel t"at is read and re3ei0es 1ro5 it (or sends to it). I1 5ore t"an one o1 t"e 3"annels are read t"en it rando5l pi3/s w"i3" one to re3ei0e 1ro5. I1 none o1 t"e 3"annels are read , t"e state5ent blo3/s 2ntil one be3o5es a0ailable. ."e select state5ent is o1ten 2sed to i5ple5ent a ti5eo2t(
select 7 case ms.$ :E R# c$: 4mt.+rintln53*essa.e $3< ms.$6 case ms. :E R# c : 4mt.+rintln53*essa.e 3< ms. 6 case R# time.W4ter5time.Second6: 4mt.+rintln53timeout36 8

-+

3reates a 3"annel and a1ter t"e !i0en d2ration will send t"e 32rrent ti5e on it. (we werenHt interested in t"e ti5e so we didnHt store it in a 0ariable) We 3an also spe3i1 a de4ault 3ase(
time.W4ter select 7 case ms.$ :E R# c$: 4mt.+rintln53*essa.e $3< ms.$6 case ms. :E R# c : 4mt.+rintln53*essa.e 3< ms. 6 case R# time.W4ter5time.Second6: 4mt.+rintln53timeout36 de4ault: 4mt.+rintln53nothin. read-36 8

."e de1a2lt 3ase "appens i55ediatel i1 none o1 t"e 3"annels are read .

-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. 'or5all 3"annels are s n3"rono2sU bot" sides o1 t"e 3"annel will wait 2ntil t"e ot"er side is read . 4 b211ered 3"annel is as n3"rono2sU sendin! or re3ei0in! a 5essa!e will not wait 2nless t"e 3"annel is alread 12ll.

Problems

=ow do o2 spe3i1 t"e dire3tion o1 a 3"annel t peO Write o2r own Sleep 12n3tion 2sin! time.W4ter. W"at is a b211ered 3"annelO =ow wo2ld o2 3reate one wit" a 3apa3it o1 2$O

-)

Pa".ages
Go was desi!ned to be a lan!2a!e t"at en3o2ra!es !ood so1tware en!ineerin! pra3ti3es. 4n i5portant part o1 "i!" F2alit so1tware is 3ode re2se G e5bodied in t"e prin3iple I%onHt >epeat <o2rsel1.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. '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. &2ndlin! 3ode in t"is wa ser0es 3 p2rposes(
4mt

It red23es t"e 3"an3e o1 "a0in! o0erlappin! na5es. ."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. It speeds 2p t"e 3o5piler b onl reF2irin! re3o5pilation o1 s5aller 3"2n/s o1 a pro!ra5. 4lt"o2!" we 2se t"e pa3/a!e 4mt, we donHt "a0e to re3o5pile it e0er ti5e we 3"an!e o2r pro!ra5.

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. Wit"o2t t"is separate pro!ra5 we "a0e no wa o1 2sin! t"e pa3/a!e we 3reate. DetHs 3reate an appli3ation t"at will 2se a pa3/a!e we will write. Create a 1older in '/2o/src/.olan.#boo& 3alled chapter$$. Inside t"at 1older 3reate a 1ile 3alled main..o w"i3" 3ontains t"is(
pac&a.e main import 34mt3 import 3.olan.#boo&/chapter$$/math3 4unc main56 7 xs :E GH4loat>@7$< <?<@8 av. :E math.Wvera.e5xs6 4mt.+rintln5av.6 8

'ow 3reate anot"er 1older inside o1 t"e chapter$$ 1older 3alled math. Inside o1 t"is 1older 3reate a 1ile 3alled math..o t"at 3ontains t"is(
pac&a.e math 4unc Wvera.e5xs GH4loat>@6 4loat>@ 7 total :E 4loat>@5/6 4or M< x :E ran.e xs 7 total BE x

6$

8 return total / 4loat>@5len5xs66 8

Esin! a ter5inal in t"e math 1older o2 N2st 3reated r2n .o install. ."is will 3o5pile t"e math..o pro!ra5 and 3reate a lin/able obNe3t 1ile( '/2o/p&./osMarch/.olan.#boo&/chapter$$/math.a. (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 .o run main..o. <o2 s"o2ld see .". So5e t"in!s to note(

is t"e na5e o1 a pa3/a!e t"at is part o1 GoHs standard distrib2tion, b2t sin3e Go pa3/a!es 3an be "ierar3"i3al we are sa1e to 2se t"e sa5e na5e 1or o2r pa3/a!e. (."e real math pa3/a!e is N2st math, o2rs is .olan.# boo&/chapter$$/math) W"en we i5port o2r 5at" librar we 2se its 12ll na5e (import 3.olan.# boo&/chapter$$/math3), b2t inside o1 t"e math..o 1ile we onl 2se t"e last part o1 t"e na5e (pac&a.e math).
math

We also onl 2se t"e s"ort na5e math w"en we re1eren3e 12n3tions 1ro5 o2r librar . I1 we wanted to 2se bot" libraries in t"e sa5e pro!ra5 Go allows 2s to 2se an alias(
import m 3.olan.#boo&/chapter$$/math3 4unc main56 7 xs :E GH4loat>@7$< <?<@8 av. :E m.Wvera.e5xs6 4mt.+rintln5av.6 8 m

is t"e alias.

<o2 5a "a0e noti3ed t"at e0er 12n3tion in t"e pa3/a!es weH0e seen start wit" a 3apital letter. 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. I1 we "ad na5ed t"e 12n3tion avera.e instead o1 Wvera.e o2r main pro!ra5 wo2ld not "a0e been 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 allows 2s to 1reel 3"an!e t"ose parts later wit"o2t "a0in! to worr abo2t brea/in! ot"er pro!ra5s, and it 5a/es o2r pa3/a!e easier to 2se.

8a3/a!e na5es 5at3" t"e 1olders t"e 1all in. ."ere are wa s aro2nd t"is, b2t itHs a lot easier i1 o2 sta wit"in t"is pattern.

$o"umentation
61

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. In a ter5inal r2n t"is 3o55and(
.odoc .olan.#boo&/chapter$$/math Wvera.e

<o2 s"o2ld see in1or5ation displa ed 1or t"e 12n3tion we N2st wrote. We 3an i5pro0e t"is do325entation b addin! a 3o55ent be1ore t"e 12n3tion(
// !inds the avera.e o4 a series o4 numbers 4unc Wvera.e5xs GH4loat>@6 4loat>@ 7

I1 o2 r2n .o install in t"e math 1older, t"en re,r2n t"e .odoc 3o55and o2 s"o2ld see o2r 3o55ent below t"e 12n3tion de1inition. ."is do325entation is also a0ailable in web 1or5 b r2nnin! t"is 3o55and(
.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.

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) 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. =ow wo2ld o2 do325ent t"e 12n3tions o2 3reated in Y3O

62

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. ."ere1ore an i5portant part o1 t"e so1tware de0elop5ent pro3ess is testin!. Writin! tests 1or o2r 3ode is a !ood wa to ens2re F2alit and i5pro0e reliabilit . Go in3l2des a spe3ial pro!ra5 t"at 5a/es writin! tests easier, so letHs 3reate so5e tests 1or t"e pa3/a!e we 5ade in t"e last 3"apter. In t"e math 1older 1ro5 chapter$$ 3reate a new 1ile 3alled mathMtest..o t"at 3ontains t"is(
pac&a.e math import 3testin.3 4unc UestWvera.e5t 9testin..U6 7 var v 4loat>@ v E Wvera.e5GH4loat>@7$< 86 i4 v KE $." 7 t.;rror53;xpected $."< .ot 3< v6 8 8

'ow r2n t"is 3o55and(


.o test

<o2 s"o2ld see t"is(


( .o test +WSS o& .olan.#boo&/chapter$$/math

/./? s

."e .o test 3o55and will loo/ 1or an tests in an o1 t"e 1iles in t"e 32rrent 1older and r2n t"e5. .ests are identi1ied b startin! a 12n3tion wit" t"e word Uest and ta/in! one ar!25ent o1 t pe 9testin..U. In o2r 3ase sin3e weHre testin! t"e Wvera.e 12n3tion we na5e t"e test 12n3tion UestWvera.e. On3e we "a0e t"e testin! 12n3tion set2p we write tests t"at 2se t"e 3ode weHre testin!. In t"is 3ase we /now t"e a0era!e o1 G$< H s"o2ld be $." so t"atHs w"at we 3"e3/. ItHs probabl a !ood idea to test 5an di11erent 3o5binations o1 n25bers so letHs 3"an!e o2r test pro!ra5 a little(
pac&a.e math import 3testin.3 t-pe testpair struct 7 values GH4loat>@ avera.e 4loat>@ 8 var tests E GHtestpair7

63

7 GH4loat>@7$< 8< $." 8< 7 GH4loat>@7$<$<$<$<$<$8< $ 8< 7 GH4loat>@7#$<$8< / 8<

4unc UestWvera.e5t 9testin..U6 7 4or M< pair :E ran.e tests 7 v :E Wvera.e5pair.values6 i4 v KE pair.avera.e 7 t.;rror5 3!or3< pair.values< 3expected3< pair.avera.e< 3.ot3< v< 6 8 8 8

."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). We 3reate a struct to represent t"e inp2ts and o2tp2ts 1or t"e 12n3tion. ."en we 3reate a list o1 t"ese structs (pairs). ."en we loop t"ro2!" ea3" one and r2n t"e 12n3tion.

Problems

Writin! a !ood s2ite o1 tests is not alwa s eas , b2t t"e pro3ess o1 writin!s tests o1ten re0eals 5ore abo2t a proble5 t"en o2 5a at 1irst reali6e. 9or exa5ple, wit" o2r Wvera.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.

64

T+e !ore Pa".ages


Instead o1 writin! e0er t"in! 1ro5 s3rat3", 5ost real world pro!ra55in! depends on o2r abilit to inter1a3e wit" existin! libraries. ."is 3"apter will ta/e a loo/ at so5e o1 t"e 5ost 3o55onl 2sed pa3/a!es in3l2ded wit" Go. 9irst a word o1 warnin!( alt"o2!" so5e o1 t"ese libraries are 1airl ob0io2s (or "a0e been explained in pre0io2s 3"apters), 5an o1 t"e libraries in3l2ded wit" Go reF2ire spe3iali6ed do5ain spe3i1i3 /nowled!e (1or exa5ple( 3r pto!rap" ). It is be ond t"e s3ope o1 t"is boo/ to explain t"ese 2nderl in! te3"nolo!ies.

trings
Go in3l2des a lar!e n25ber o1 12n3tions to wor/ wit" strin!s in t"e strin.s pa3/a!e(
pac&a.e main import 5 34mt3 3strin.s3 6 4unc main56 7 4mt.+rintln5 // true strin.s.Contains53test3< 3es36< // strin.s.Count53test3< 3t36< // true strin.s.0as+re4ix53test3< 3te36< // true strin.s.0asSu44ix53test3< 3st36< // $ strin.s.:ndex53test3< 3e36< // 3a#b3 strin.s.]oin5GHstrin.73a3<3b38< 3#36< // EE 3aaaaa3 strin.s.\epeat53a3< "6< // 3bbaa3 strin.s.\eplace53aaaa3< 3a3< 3b3< // GHstrin.73a3<3b3<3c3<3d3<3e38 strin.s.Split53a#b#c#d#e3< 3#36< // 3test3 strin.s.Uo,o)er53U;SU36< // 3U;SU3 strin.s.UoUpper53test36< 6<

6-

6 8

So5eti5es we need to wor/ wit" strin!s as binar data. .o 3on0ert a strin! to a sli3e o1 b tes (and 0i3e,0ersa) do t"is(
arr :E GHb-te53test36 str :E strin.5GHb-te7NtN<NeN<NsN<NtN86

In#ut - .ut#ut
&e1ore we loo/ at 1iles we need to 2nderstand GoHs io pa3/a!e. ."e io pa3/a!e 3onsists o1 a 1ew 12n3tions, b2t 5ostl inter1a3es 2sed in ot"er pa3/a!es. ."e two 5ain inter1a3es are \eader and 1riter. \eaders s2pport readin! 0ia t"e \ead 5et"od. 1riters s2pport writin! 0ia t"e 1rite 5et"od. @an 12n3tions in Go ta/e \eaders or 1riters as ar!25ents. 9or exa5ple t"e io pa3/a!e "as a Cop- 12n3tion w"i3" 3opies data 1ro5 a \eader to a 1riter(
4unc Cop-5dst 1riter< src \eader6 5)ritten int>@< err error6

.o read or write to a GHb-te or a strin. o2 3an 2se t"e Bu44er str23t 1o2nd in t"e b-tes pa3/a!e(
var bu4 b-tes.Bu44er bu4.1rite5GHb-te53test366

4 Bu44er doesnHt "a0e to be initiali6ed and s2pports bot" t"e \eader and 1riter inter1a3es. <o2 3an 3on0ert it into a GHb-te b 3allin! bu4.B-tes56. I1 o2 onl need to read 1ro5 a strin! o2 3an also 2se t"e strin.s.Ne)\eader 12n3tion w"i3" is 5ore e11i3ient t"an 2sin! a b211er.

Files * Folders
.o open a 1ile in Go 2se t"e Tpen 12n3tion 1ro5 t"e os pa3/a!e. =ere is an exa5ple o1 "ow to read t"e 3ontents o1 a 1ile and displa t"e5 on t"e ter5inal(
pac&a.e main import 5 34mt3 3os3 6 4unc main56 7 4ile< err :E os.Tpen53test.txt36 i4 err KE nil 7 // handle the error here return 8 de4er 4ile.Close56 // .et the 4ile siZe

66

stat< err :E 4ile.Stat56 i4 err KE nil 7 return 8 // read the 4ile bs :E ma&e5GHb-te< stat.SiZe566 M< err E 4ile.\ead5bs6 i4 err KE nil 7 return 8 str :E strin.5bs6 4mt.+rintln5str6

We 2se de4er 4ile.Close56 ri!"t a1ter openin! t"e 1ile to 5a/e s2re t"e 1ile is 3losed as soon as t"e 12n3tion 3o5pletes. >eadin! 1iles is 0er 3o55on, so t"ereHs a s"orter wa to do t"is(
pac&a.e main import 5 34mt3 3io/ioutil3 6 4unc main56 7 bs< err :E ioutil.\ead!ile53test.txt36 i4 err KE nil 7 return 8 str :E strin.5bs6 4mt.+rintln5str6 8

=ere is "ow we 3an 3reate a 1ile(


pac&a.e main import 5 3os3 6 4unc main56 7 4ile< err :E os.Create53test.txt36 i4 err KE nil 7 // handle the error here return 8 de4er 4ile.Close56 4ile.1riteStrin.53test36 8

.o !et t"e 3ontents o1 a dire3tor we 2se t"e sa5e os.Tpen 12n3tion b2t !i0e it a dire3tor pat" instead o1 a 1ile na5e. ."en we 3all t"e \eaddir 5et"od(
pac&a.e main

6*

import 5 34mt3 3os3 6 4unc main56 7 dir< err :E os.Tpen53.36 i4 err KE nil 7 return 8 de4er dir.Close56 4ile:n4os< err :E dir.\eaddir5#$6 i4 err KE nil 7 return 8 4or M< 4i :E ran.e 4ile:n4os 7 4mt.+rintln54i.Name566 8 8

O1ten we want to re32rsi0el wal/ a 1older (read t"e 1olderHs 3ontents, all t"e s2b, 1olders, all t"e s2b,s2b,1olders, M). .o 5a/e t"is easier t"ereHs a 1al& 12n3tion pro0ided in t"e path/4ilepath pa3/a!e(
pac&a.e main import 5 34mt3 3os3 3path/4ilepath3 6 4unc main56 7 4ilepath.1al&53.3< 4unc5path strin.< in4o os.!ile:n4o< err error6 error 7 4mt.+rintln5path6 return nil 86 8

."e 12n3tion o2 pass to 1al& is 3alled 1or e0er 1ile and 1older in t"e root 1older. (in t"is 3ase .)

Errors
Go "as a b2ilt,in t pe 1or errors t"at we "a0e alread seen (t"e error t pe). We 3an 3reate o2r own errors b 2sin! t"e Ne) 12n3tion in t"e errors pa3/a!e(
pac&a.e main import 3errors3 4unc main56 7 err :E errors.Ne)53error messa.e36 8

6+

Containers * ort
In addition to lists and 5aps Go "as se0eral 5ore 3olle3tions a0ailable 2nderneat" t"e 3ontainer pa3/a!e. WeHll ta/e a loo/ at t"e container/list pa3/a!e as an exa5ple.

/ist
."e container/list pa3/a!e i5ple5ents a do2bl ,lin/ed list. 4 lin/ed list is a t pe o1 data str23t2re t"at loo/s li/e t"is(

;a3" node o1 t"e list 3ontains a 0al2e (1, 2, or 3 in t"is 3ase) and a pointer to t"e next node. Sin3e t"is is a do2bl ,lin/ed list ea3" node will also "a0e pointers to t"e pre0io2s node. ."is list 3o2ld be 3reated b t"is pro!ra5(
pac&a.e main import 534mt3 Q 3container/list36 4unc main56 7 var x list.,ist x.+ushBac&5$6 x.+ushBac&5 6 x.+ushBac&5?6 4or e :E x.!ront56Q e KE nilQ eEe.Next56 7 4mt.+rintln5e.Value.5int66 8

."e 6ero 0al2e 1or a ,ist is an e5pt list (a 9,ist 3an also be 3reated 2sin! list.Ne)). ?al2es are appended to t"e list 2sin! +ushBac&. We loop o0er ea3" ite5 in t"e list b !ettin! t"e 1irst ele5ent, and 1ollowin! all t"e lin/s 2ntil we rea3" nil.

Sort
."e sort pa3/a!e 3ontains 12n3tions 1or sortin! arbitrar data. ."ere are se0eral prede1ined sortin! 12n3tions (1or sli3es o1 ints and 1loats) =ereHs an exa5ple 1or "ow to sort o2r own data(
pac&a.e main import 534mt3 Q 3sort36 t-pe +erson struct 7 Name strin. W.e int 8 t-pe B-Name GH+erson

6)

4unc 5this B-Name6 ,en56 int 7 return len5this6 8 4unc 5this B-Name6 ,ess5i< j int6 bool 7 return thisGiH.Name R thisGjH.Name 8 4unc 5this B-Name6 S)ap5i< j int6 7 thisGiH< thisGjH E thisGjH< thisGiH 8 4unc main56 7 &ids :E GH+erson7 73]ill3<A8< 73]ac&3<$/8< 8 sort.Sort5B-Name5&ids66 4mt.+rintln5&ids6 8

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

*$

4unc main56 7 h :E crc? .Ne):;;;56 h.1rite5GHb-te53test366 v :E h.Sum? 56 4mt.+rintln5v6 8

."e crc? "as" obNe3t i5ple5ents t"e 1riter inter1a3e, so we 3an write b tes to it li/e an ot"er 1riter. On3e weH0e written e0er t"in! we want we 3all Sum? 56 to ret2rn a uint? . 4 3o55on 2se 1or crc? is to 3o5pare two 1iles. I1 t"e Sum? 0al2e 1or bot" 1iles is t"e sa5e, itHs "i!"l li/el (t"o2!" not 1$$R 3ertain) t"at t"e 1iles are t"e sa5e. I1 t"e 0al2es are di11erent t"en t"e 1iles are de1initel not t"e sa5e(
pac&a.e main import 5 34mt3 3hash/crc? 3 3io/ioutil3 6 4unc .et0ash54ilename strin.6 5uint? < error6 7 bs< err :E ioutil.\ead!ile54ilename6 i4 err KE nil 7 return /< err 8 h :E crc? .Ne):;;;56 h.1rite5bs6 return h.Sum? 56< nil 8 4unc main56 7 h$< err :E .et0ash53test$.txt36 i4 err KE nil 7 return 8 h < err :E .et0ash53test .txt36 i4 err KE nil 7 return 8 4mt.+rintln5h$< h < h$ EE h 6 8

Cr pto!rap"i3 "as" 12n3tions are si5ilar to t"eir non,3r pto!rap"i3 3o2nterparts, 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, itHs extre5el di11i32lt to deter5ine w"at 5ade t"e "as". ."ese "as"es are o1ten 2sed in se32rit appli3ations. One 3o55on 3r pto!rap"i3 "as" 12n3tion is /nown as S=4,1. =ereHs "ow it is 2sed(
pac&a.e main import 5 34mt3 3cr-pto/sha$3 6 4unc main56 7

*1

h :E sha$.Ne)56 h.1rite5GHb-te53test366 bs :E h.Sum5GHb-te786 4mt.+rintln5bs6 8

."is exa5ple is 0er si5ilar to t"e crc? one, be3a2se bot" crc? and sha$ i5ple5ent t"e hash.0ash inter1a3e. ."e 5ain di11eren3e is t"at w"ereas crc? 3o5p2tes a 32 bit "as", sha$ 3o5p2tes a 16$ bit "as". ."ere is no nati0e t pe to represent a 16$ bit n25ber, so we 2se a sli3e o1 2$ b tes instead.

er+ers
Writin! networ/ ser0ers in Go is 0er eas . We will 1irst ta/e a loo/ at "ow to 3reate a .C8 ser0er(
pac&a.e main import 5 3encodin./.ob3 34mt3 3net3 6 4unc server56 7 // listen on a port ln< err :E net.,isten53tcp3< 3:AAAA36 i4 err KE nil 7 4mt.+rintln5err6 return 8 4or 7 // accept a connection c< err :E ln.Wccept56 i4 err KE nil 7 4mt.+rintln5err6 continue 8 // handle the connection .o handleServerConnection5c6 8 8 4unc handleServerConnection5c net.Conn6 7 // receive the messa.e var ms. strin. err :E .ob.Ne)%ecoder5c6.%ecode5Ims.6 i4 err KE nil 7 4mt.+rintln5err6 8 else 7 4mt.+rintln53\eceived3< ms.6 8 8 c.Close56

4unc client56 7 // connect to the server

*2

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

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

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

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

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

*6

Next Steps
We now "a0e all t"e in1or5ation we need to write 5ost Go pro!ra5s. &2t it wo2ld be dan!ero2s to 3on3l2de t"at t"ere1ore we are 3o5petent pro!ra55ers. 8ro!ra55in! is as 523" a 3ra1t as it is N2st "a0in! /nowled!e. ."is 3"apter will pro0ide o2 wit" so5e s2!!estions abo2t "ow best to 5aster t"e 3ra1t o1 pro!ra55in!.

tud' the %asters


8art o1 be3o5in! a !ood artist or writer is st2d in! t"e wor/s o1 t"e 5asters. ItHs no di11erent wit" pro!ra55in!. 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. Go is well s2ited to t"is tas/ sin3e t"e so2r3e 3ode 1or t"e entire proNe3t is 1reel a0ailable. 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!.or!Csr3Cp/!CioCio2tilCio2til.!o >ead t"e 3ode slowl and deliberatel . .r to 2nderstand e0er line and read t"e s2pplied 3o55ents. 9or exa5ple in t"e \ead!ile 5et"od t"ereHs a 3o55ent t"at sa s t"is(
// // // // :tNs a .ood but not certain bet that !ile:n4o )ill tell us exactl- ho) much to read< so letNs tr- it but be prepared 4or the ans)er to be )ron..

."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. 4ll o1 t"e so2r3e 3ode 1or all o1 t"e pa3/a!es is a0ailable at( "ttp(CC!olan!.or!Csr3Cp/!C

%ake omething
One o1 t"e best wa s to "one o2r s/ills is to pra3ti3e 3odin!. ."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 ;2ler ("ttp(CCproNe3te2ler.netC) or tr o2r "and at a lar!er proNe3t. 8er"aps tr to i5ple5ent a web ser0er or write a si5ple !a5e.

Team 1#
@ost real,world so1tware proNe3ts are done in tea5s, t"ere1ore learnin! "ow to wor/ in a tea5 is 3r23ial. I1 o2 3an, 1ind a 1riend G 5a be a 3lass5ate G and tea5 2p on a proNe3t. Dearn "ow to di0ide a proNe3t into pie3es o2 3an bot" wor/ on si52ltaneo2sl . **

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

*+

You might also like