Você está na página 1de 165

An InfroducfIon fo IrogrnmmIng In Co

CoyrIghf 20l2 by CnIob oxsoy


AII rIghfs rosorvod. o nrf of fhIs book mny bo
roroducod or frnnsmIffod In nny form or by nny
monns, oIocfronIc or mochnnIcnI, IncIudIng
hofocoyIng, rocordIng, or by nny InformnfIon sforngo
nnd rofrIovnI sysfom wIfhouf fho wrIffon ormIssIon of
fho nufhor, oxcof whoro ormIffod by Inw.
ISI: 9?8-l4?8355823
Covor nrf by AbIgnII oxsoy Andorson.
IorfIons of fhIs foxf nro roroducod from work cronfod
nnd shnrod by CoogIo nnd usod nccordIng fo forms
doscrIbod In fho CronfIvo Commons 3.0 AffrIbufIon
!Iconso.
Contents
1 Getting Started 1
l.l IIIos nnd IoIdors 2
l.2 Tho TormInnI 5
l.3 Toxf IdIfors 9
l.4 Co TooIs l3
2 Your First Program 15
2.l How fo !ond n Co Irogrnm l?
3 Types 23
3.l umbors 24
3.2 SfrIngs 29
3.3 IooIonns 3l
4 Variables 35
4.l How fo nmo n VnrInbIo 39
4.2 Scoo 40
4.3 Consfnnfs 43
4.4 ofInIng MuIfIIo VnrInbIos 44
4.5 An IxnmIo Irogrnm 45
5 Control Structures 4
5.l Ior 48
5.2 If 5l
5.3 SwIfch 55
! "rrays# Slices and $aps 5%
6.l Arrnys 58
6.2 SIIcos 64
6.3 Mns 6?
Functions !
?.l Your Socond IuncfIon ??
?.2 !ofurnIng MuIfIIo VnIuos 82
?.3 VnrIndIc IuncfIons 82
?.4 CIosuro 84
?.5 !ocursIon 86
?.6 ofor, InnIc & !ocovor 88
% Pointers &2
8.l Tho * nnd & oornfors 93
8.2 now 94
& Structs and 'nter(aces &
9.l Sfrucfs 98
9.2 Mofhods l0l
9.3 Inforfncos l04
1) Concurrency 1)%
l0.l CoroufInos l08
l0.2 ChnnnoIs lll
11 Pac*ages 12)
ll.l CronfIng Inckngos l2l
ll.2 ocumonfnfIon l24
12 Testing 12
13 T+e Core Pac*ages 132
l3.l SfrIngs l32
l3.2 Inuf / Oufuf l34
l3.3 IIIos & IoIdors l35
l3.4 Irrors l40
l3.5 ConfnInors & Sorf l4l
l3.6 Hnshos & Cryfogrnhy l44
l3.? Sorvors l4?
l3.8 InrsIng Commnnd !Ino Argumonfs l55
l3.9 SynchronIznfIon IrImIfIvos l56
14 ,e-t Steps 15&
l4.l Sfudy fho Mnsfors l59
l4.2 Mnko SomofhIng l60
l4.3 Tonm ! l6l
1 Getting Started
Comufor rogrnmmIng Is fho nrf, crnff nnd scIonco of
wrIfIng rogrnms whIch dofIno how comufors oornfo.
ThIs book wIII fonch you how fo wrIfo comufor ro-
grnms usIng n rogrnmmIng Inngungo dosIgnod by
CoogIo nnmod Co.
Co Is n gonornI uroso rogrnmmIng Inngungo wIfh
ndvnncod fonfuros nnd n cIonn synfnx. Iocnuso of Ifs
wIdo nvnIInbIIIfy on n vnrIofy of Infforms, Ifs robusf
woII-documonfod common IIbrnry, nnd Ifs focus on
good soffwnro ongInoorIng rIncIIos, Co Is nn IdonI
Inngungo fo Ionrn ns your fIrsf rogrnmmIng Inngungo.
Tho rocoss wo uso fo wrIfo soffwnro usIng Co (nnd
mosf rogrnmmIng Inngungos) Is fnIrIy sfrnIghffor-
wnrd:
l. Cnfhor roquIromonfs
2. IInd n soIufIon
3. WrIfo sourco codo fo ImIomonf fho soIufIon
1
Getting Started 2
4. ComIIo fho sourco codo Info nn oxocufnbIo
5. !un nnd fosf fho rogrnm fo mnko suro If works
ThIs rocoss Is IfornfIvo (monnIng Ifs dono mnny
fImos) nnd fho sfos usunIIy ovorIn. Iuf boforo wo
wrIfo our fIrsf rogrnm In Co fhoro nro n fow roroquI-
sIfo concofs wo nood fo undorsfnnd.
1.1 Files and Folders
A fIIo Is n coIIocfIon of dnfn sforod ns n unIf wIfh n
nnmo. Modorn oornfIng sysfoms (IIko WIndows or
Mnc OSX) confnIn mIIIIons of fIIos whIch sforo n Inrgo
vnrIofy of dIfforonf fyos of InformnfIon ovoryfhIng
from foxf documonfs fo oxocufnbIo rogrnms fo muIfI-
modIn fIIos.
AII fIIos nro sforod In fho snmo wny on n comufor:
fhoy nII hnvo n nnmo, n dofInIfo sIzo (monsurod In
byfos) nnd nn nssocInfod fyo. TyIcnIIy fho fIIo's fyo
Is sIgnIfIod by fho fIIo's oxfonsIon fho nrf of fho fIIo
nnmo fhnf comos nffor fho Insf .. Ior oxnmIo n fIIo
wIfh fho nnmo hello.txt hns fho oxfonsIon txt whIch
Is usod fo rorosonf foxfunI dnfn.
IoIdors (nIso cnIIod dIrocforIos) nro usod fo grou fIIos
fogofhor. Thoy cnn nIso confnIn ofhor foIdors. On WIn-
3 Getting Started
dows fIIo nnd foIdor nfhs (IocnfIons) nro rorosonfod
wIfh fho \ (bncksInsh) chnrncfor, for oxnmIo:
C:\Users\john\example.txt. example.txt Is fho fIIo
nnmo, If Is confnInod In fho foIdor john, whIch Is IfsoIf
confnInod In fho foIdor Users whIch Is sforod on drIvo C
(whIch rorosonfs fho rImnry hysIcnI hnrd drIvo In
WIndows). On OSX (nnd mosf ofhor oornfIng sys-
foms) fIIo nnd foIdor nfhs nro rorosonfod wIfh fho /
(forwnrd sInsh) chnrncfor, for oxnmIo:
/Users/john/example.txt. !Iko on WIndows
example.txt Is fho fIIo nnmo, If Is confnInod In fho
foIdor john, whIch Is In fho foIdor Users. !nIIko WIn-
dows, OSX doos nof socIfy n drIvo Ioffor whoro fho fIIo
Is sforod.
Getting Started 4
/indo0s
On WIndows fIIos nnd foIdors cnn bo browsod usIng
WIndows IxIoror (nccossIbIo by doubIo-cIIckIng My
Comufor or fyIng wIn+o):
5 Getting Started
1S2
On OSX fIIos nnd foIdors cnn bo browsod usIng IIndor
(nccossIbIo by cIIckIng fho IIndor Icon fho fnco Icon
In fho Iowor Ioff bnr):
1.2 T+e Terminal
Mosf of fho InforncfIons wo hnvo wIfh comufors fodny
nro fhrough sohIsfIcnfod grnhIcnI usor Inforfncos
(C!Is). Wo uso koybonrds, mIco nnd fouchscroons fo
Inforncf wIfh vIsunI buffons or ofhor fyos of confroIs
fhnf nro dIsInyod on n scroon.
If wnsn'f nIwnys fhIs wny. Ioforo fho C!I wo hnd fho
formInnI n sImIor foxfunI Inforfnco fo fho comufor
Getting Started 6
whoro rnfhor fhnn mnnIuInfIng buffons on n scroon
wo Issuod commnnds nnd rocoIvod roIIos. Wo hnd n
convorsnfIon wIfh fho comufor.
And nIfhough If mIghf nonr fhnf mosf of fho comuf-
Ing worId hns Ioff bohInd fho formInnI ns n roIIc of fho
nsf, fho frufh Is fhnf fho formInnI Is sfIII fho fundn-
monfnI usor Inforfnco usod by mosf rogrnmmIng Inn-
gungos on mosf comufors. Tho Co rogrnmmIng Inn-
gungo Is no dIfforonf, nnd so boforo wo wrIfo n rogrnm
In Co wo nood fo hnvo n rudImonfnry undorsfnndIng of
how n formInnI works.
/indo0s
In WIndows fho formInnI (nIso known ns fho commnnd
IIno) cnn bo broughf u by fyIng fho wIndows koy + r
(hoId down fho wIndows koy fhon ross r), fyIng
cmd.exe nnd hIffIng onfor. You shouId soo n bInck wIn-
dow nonr fhnf Iooks IIko fhIs:
7 Getting Started
Iy dofnuIf fho commnnd IIno sfnrfs In your homo dI-
rocfory. (In my cnso fhIs Is C:\Users\caleb) You Issuo
commnnds by fyIng fhom In nnd hIffIng onfor. Try
onforIng fho commnnd dir, whIch IIsfs fho confonfs of
n dIrocfory. You shouId soo somofhIng IIko fhIs:
C:\Users\caleb>dir
Volume in drive C has no label.
Volume Serial Number is B!"#!$"
IoIIowod by n IIsf of fho fIIos nnd foIdors confnInod In
your homo dIrocfory. You cnn chnngo dIrocforIos by us-
Ing fho commnnd cd. Ior oxnmIo you robnbIy hnvo n
foIdor cnIIod %es&top. You cnn soo Ifs confonfs by on-
forIng cd %es&top nnd fhon onforIng dir. To go bnck fo
your homo dIrocfory you cnn uso fho socInI dIrocfory
nnmo .. (fwo orIods noxf fo onch ofhor): cd ... A sIn-
gIo orIod rorosonfs fho curronf foIdor (known ns fho
workIng foIdor), so cd . doosn'f do nnyfhIng. Thoro nro
Getting Started 8
n Iof moro commnnds you cnn uso, buf fhIs shouId bo
onough fo gof you sfnrfod.
1S2
In OSX fho formInnI cnn bo ronchod by goIng fo IIndor
AIIcnfIons !fIIIfIos TormInnI. You shouId
soo n wIndow IIko fhIs:
Iy dofnuIf fho formInnI sfnrfs In your homo dIrocfory.
(In my cnso fhIs Is /Users/caleb) You Issuo commnnds
by fyIng fhom In nnd hIffIng onfor. Try onforIng fho
commnnd ls, whIch IIsfs fho confonfs of n dIrocfory.
You shouId soo somofhIng IIko fhIs:
9 Getting Started
caleb#min:' caleb( ls
%es&top %o)nloads *ovies +ictures
%ocuments ,ibrar- *usic +ublic
Thoso nro fho fIIos nnd foIdors confnInod In your homo
dIrocfory (In fhIs cnso fhoro nro no fIIos). You cnn
chnngo dIrocforIos usIng fho cd commnnd. Ior oxnmIo
you robnbIy hnvo n foIdor cnIIod %es&top. You cnn soo
Ifs confonfs by onforIng cd %es&top nnd fhon onforIng
ls. To go bnck fo your homo dIrocfory you cnn uso fho
socInI dIrocfory nnmo .. (fwo orIods noxf fo onch
ofhor): cd ... A sIngIo orIod rorosonfs fho curronf
foIdor (known ns fho workIng foIdor), so cd . doosn'f do
nnyfhIng. Thoro nro n Iof moro commnnds you cnn uso,
buf fhIs shouId bo onough fo gof you sfnrfod.
1.3 Te-t 3ditors
Tho rImnry fooI rogrnmmors uso fo wrIfo soffwnro Is
n foxf odIfor. Toxf odIfors nro sImIInr fo word rocoss-
Ing rogrnms (MIcrosoff Word, Oon OffIco, .) buf un-
IIko such rogrnms fhoy don'f do nny formnffIng, (o
boId, IfnIIc, .) Insfond fhoy oornfo onIy on InIn foxf.
Iofh OSX nnd WIndows como wIfh foxf odIfors buf
fhoy nro hIghIy IImIfod nnd I rocommond InsfnIIIng n
boffor ono.
To mnko fho InsfnIInfIon of fhIs soffwnro onsIor nn In-
Getting Started 10
sfnIIor Is nvnIInbIo nf fho book's wobsIfo:
http://)))..olan.#boo&.com/. ThIs InsfnIIor wIII In-
sfnII fho Co fooI suIfo, sofu onvIronmonfnI vnrInbIos
nnd InsfnII n foxf odIfor.
/indo0s
Ior wIndows fho InsfnIIor wIII InsfnII fho ScIfo foxf od-
Ifor. You cnn oon If by goIng fo Sfnrf AII Irogrnms
Co ScIfo. You shouId soo somofhIng IIko fhIs:
Tho foxf odIfor confnIns n Inrgo whIfo foxf nron whoro
foxf cnn bo onforod. To fho Ioff of fhIs foxf nron you
cnn soo fho IIno numbors. Af fho boffom of fho wIndow
11 Getting Started
Is n sfnfus bnr whIch dIsInys InformnfIon nbouf fho
fIIo nnd your curronf IocnfIon In If (rIghf now If snys
fhnf wo nro on IIno l, coIumn l, foxf Is boIng Insorfod
normnIIy, nnd wo nro usIng wIndows-sfyIo nowIInos).
You cnn oon fIIos by goIng fo IIIo Oon nnd brows-
Ing fo your dosIrod fIIo. IIIos cnn bo snvod by goIng fo
IIIo Snvo or IIIo Snvo As.
As you work In n foxf odIfor If Is usofuI fo Ionrn koy-
bonrd shorfcufs. Tho monus IIsf fho shorfcufs fo fhoIr
rIghf. Horo nro n fow of fho mosf common:
CfrI + S snvo fho curronf fIIo
CfrI + X cuf fho curronfIy soIocfod foxf (romovo If
nnd uf If In your cIIbonrd so If cnn bo nsfod Infor)
CfrI + C coy fho curronfIy soIocfod foxf
CfrI + V nsfo fho foxf curronfIy In fho cIIbonrd
!so fho nrrow koys fo nnvIgnfo, Homo fo go fo fho
bogInnIng of fho IIno nnd Ind fo go fo fho ond of fho
IIno
HoId down shIff whIIo usIng fho nrrow koys (or
Homo nnd Ind) fo soIocf foxf wIfhouf usIng fho
mouso
CfrI + I brIngs u n fInd In fIIo dInIog fhnf you cnn
uso fo sonrch fho confonfs of n fIIo
Getting Started 12
1S2
Ior OSX fho InsfnIIor InsfnIIs fho Toxf WrnngIor foxf
odIfor:
!Iko ScIfo on WIndows Toxf WrnngIor confnIns n Inrgo
whIfo nron whoro foxf Is onforod. IIIos cnn bo oonod
by goIng fo IIIo Oon. IIIos cnn bo snvod by goIng fo
IIIo Snvo or IIIo Snvo As. Horo nro somo usofuI
koybonrd shorfcufs: (Commnnd Is fho koy)
13 Getting Started
Commnnd + S snvo fho curronf fIIo
Commnnd + X cuf fho curronfIy soIocfod foxf (ro-
movo If nnd uf If In your cIIbonrd so If cnn bo
nsfod Infor)
Commnnd + C coy fho curronfIy soIocfod foxf
Commnnd + V nsfo fho foxf curronfIy In fho cII-
bonrd
!so fho nrrow koys fo nnvIgnfo
Commnnd + I brIngs u n fInd In fIIo dInIog fhnf
you cnn uso fo sonrch fho confonfs of n fIIo
1.4 Go Tools
Co Is n comIIod rogrnmmIng Inngungo, whIch monns
sourco codo (fho codo you wrIfo) Is frnnsInfod Info n
Inngungo fhnf your comufor cnn undorsfnnd. Thoro-
foro boforo wo cnn wrIfo n Co rogrnm, wo nood fho Co
comIIor.
Tho InsfnIIor wIII sofu Co for you nufomnfIcnIIy. Wo
wIII bo usIng vorsIon l of fho Inngungo. (Moro Informn-
fIon cnn bo found nf http://)))..olan..or.)
!of's mnko suro ovoryfhIng Is workIng. Oon u n for-
mInnI nnd fyo fho foIIowIng:
.o version
Getting Started 14
You shouId soo fho foIIowIng:
.o version .o$./.
Your vorsIon numbor mny bo sIIghfIy dIfforonf. If you
gof nn orror nbouf fho commnnd nof boIng rocognIzod
fry rosfnrfIng your comufor.
Tho Co fooI suIfo Is mndo u of sovornI dIfforonf com-
mnnds nnd sub-commnnds. A IIsf of fhoso commnnds Is
nvnIInbIo by fyIng:
.o help
Wo wIII soo how fhoy nro usod In subsoquonf chnfors.
2 Your First Program
TrndIfIonnIIy fho fIrsf rogrnm you wrIfo In nny ro-
grnmmIng Inngungo Is cnIIod n HoIIo WorId rogrnm
n rogrnm fhnf sImIy oufufs 0ello 1orld fo your
formInnI. !of's wrIfo ono usIng Co.
IIrsf cronfo n now foIdor whoro wo cnn sforo our ro-
grnm. Tho InsfnIIor you usod In chnfor l cronfod n
foIdor In your homo dIrocfory nnmod 2o. Cronfo n
foIdor nnmod '/2o/src/.olan.#boo&/chapter. (Whoro
' monns your homo dIrocfory) Irom fho formInnI you
cnn do fhIs by onforIng fho foIIowIng commnnds:
m&dir 2o/src/.olan.#boo&
m&dir 2o/src/.olan.#boo&/chapter
!sIng your foxf odIfor fyo In fho foIIowIng:
15
Your First Program 16
pac&a.e main
import 34mt3
// this is a comment
4unc main56 7
4mt.+rintln530ello 1orld36
8
Mnko suro your fIIo Is IdonfIcnI fo whnf Is shown horo
nnd snvo If ns main..o In fho foIdor wo jusf cronfod.
Oon u n now formInnI nnd fyo In fho foIIowIng:
cd 2o/src/.olan.#boo&/chapter
.o run main..o
You shouId soo 0ello 1orld dIsInyod In your formI-
nnI. Tho .o run commnnd fnkos fho subsoquonf fIIos
(sonrnfod by sncos), comIIos fhom Info nn oxo-
cufnbIo snvod In n fomornry dIrocfory nnd fhon runs
fho rogrnm. If you dIdn'f soo 0ello 1orld dIsInyod
you mny hnvo mndo n mIsfnko whon fyIng In fho ro-
grnm. Tho Co comIIor wIII gIvo you hInfs nbouf whoro
fho mIsfnko IIos. !Iko mosf comIIors, fho Co comIIor
Is oxfromoIy odnnfIc nnd hns no foIornnco for mIs-
fnkos.
17 Your First Program
2.1 4o0 to 5ead a Go Program
!of's Iook nf fhIs rogrnm In moro dofnII. Co rogrnms
nro rond fo fo boffom, Ioff fo rIghf. (IIko n book) Tho
fIrsf IIno snys fhIs:
pac&a.e main
ThIs Is know ns n nckngo docInrnfIon. Ivory Co ro-
grnm musf sfnrf wIfh n nckngo docInrnfIon. Inckngos
nro Co's wny of orgnnIzIng nnd rousIng codo. Thoro nro
fwo fyos of Co rogrnms: oxocufnbIos nnd IIbrnrIos.
IxocufnbIo nIIcnfIons nro fho kInds of rogrnms fhnf
wo cnn run dIrocfIy from fho formInnI. (In WIndows
fhoy ond wIfh .exe) !IbrnrIos nro coIIocfIons of codo
fhnf wo nckngo fogofhor so fhnf wo cnn uso fhom In
ofhor rogrnms. Wo wIII oxIoro IIbrnrIos In moro do-
fnII Infor, for now jusf mnko suro fo IncIudo fhIs IIno In
nny rogrnm you wrIfo.
Tho noxf IIno Is n bInnk IIno. Comufors rorosonf
nowIInos wIfh n socInI chnrncfor (or sovornI chnrnc-
fors). owIInos, sncos nnd fnbs nro known ns whIfo-
snco (bocnuso you cnn'f soo fhom). Co mosfIy doosn'f
cnro nbouf whIfosnco, wo uso If fo mnko rogrnms
onsIor fo rond. (You couId romovo fhIs IIno nnd fho ro-
grnm wouId bohnvo In oxncfIy fho snmo wny)
Your First Program 18
Thon wo soo fhIs:
import 34mt3
Tho import koyword Is how wo IncIudo codo from ofhor
nckngos fo uso wIfh our rogrnm. Tho 4mt nckngo
(shorfhnnd for formnf) ImIomonfs formnffIng for In-
uf nnd oufuf. CIvon whnf wo jusf Ionrnod nbouf
nckngos whnf do you fhInk fho 4mt nckngo's fIIos
wouId confnIn nf fho fo of fhom
ofIco fhnf 4mt nbovo Is surroundod by doubIo quofos.
Tho uso of doubIo quofos IIko fhIs Is known ns n sfrIng
IIfornI whIch Is n fyo of oxrossIon. In Co sfrIngs
rorosonf n soquonco of chnrncfors (Ioffors, numbors,
symboIs, .) of n dofInIfo Iongfh. SfrIngs nro doscrIbod
In moro dofnII In fho noxf chnfor, buf for now fho Im-
orfnnf fhIng fo koo In mInd Is fhnf nn oonIng 3
chnrncfor musf ovonfunIIy bo foIIowod by nnofhor 3
chnrncfor nnd nnyfhIng In bofwoon fho fwo Is IncIudod
In fho sfrIng. (Tho 3 chnrncfor IfsoIf Is nof nrf of fho
sfrIng)
Tho IIno fhnf sfnrfs wIfh // Is known ns n commonf.
Commonfs nro Ignorod by fho Co comIIor nnd nro
fhoro for your own snko (or whoovor Icks u fho
sourco codo for your rogrnm). Co suorfs fwo dIffor-
19 Your First Program
onf sfyIos of commonfs: // commonfs In whIch nII fho
foxf bofwoon fho // nnd fho ond of fho IIno Is nrf of
fho commonf nnd /9 9/ commonfs whoro ovoryfhIng
bofwoon fho 9s Is nrf of fho commonf. (And mny In-
cIudo muIfIIo IInos)
Affor fhIs you soo n funcfIon docInrnfIon:
4unc main56 7
4mt.+rintln530ello 1orld36
8
IuncfIons nro fho buIIdIng bIocks of n Co rogrnm.
Thoy hnvo Inufs, oufufs nnd n sorIos of sfos cnIIod
sfnfomonfs whIch nro oxocufod In ordor. AII funcfIons
sfnrf wIfh fho koyword 4unc foIIowod by fho nnmo of
fho funcfIon (main In fhIs cnso), n IIsf of zoro or moro
nrnmofors surroundod by nronfhosos, nn ofIonnI
rofurn fyo nnd n body whIch Is surroundod by curIy
brncos. ThIs funcfIon hns no nrnmofors, doosn'f ro-
furn nnyfhIng nnd hns onIy ono sfnfomonf. Tho nnmo
main Is socInI bocnuso If's fho funcfIon fhnf gofs cnIIod
whon you oxocufo fho rogrnm.
Tho fInnI Ioco of our rogrnm Is fhIs IIno:
4mt.+rintln530ello 1orld36
Your First Program 20
ThIs sfnfomonf Is mndo of fhroo comononfs. IIrsf wo
nccoss nnofhor funcfIon InsIdo of fho 4mt nckngo
cnIIod +rintln (fhnf's fho 4mt.+rintln Ioco, +rintln
monns IrInf !Ino). Thon wo cronfo n now sfrIng fhnf
confnIns 0ello 1orld nnd Invoko (nIso known ns cnII or
oxocufo) fhnf funcfIon wIfh fho sfrIng ns fho fIrsf nnd
onIy nrgumonf.
Af fhIs oInf wo'vo nIrondy soon n Iof of now formInoI-
ogy nnd you mny bo n bIf ovorwhoImod. SomofImos Ifs
hoIfuI fo doIIbornfoIy rond your rogrnm ouf Ioud.
Ono rondIng of fho rogrnm wo jusf wrofo mIghf go
IIko fhIs:
Cronfo n now oxocufnbIo rogrnm, whIch roforoncos
fho 4mt IIbrnry nnd confnIns ono funcfIon cnIIod
main. Thnf funcfIon fnkos no nrgumonfs, doosn'f ro-
furn nnyfhIng nnd doos fho foIIowIng: Accoss fho
+rintln funcfIon confnInod InsIdo of fho 4mt nck-
ngo nnd Invoko If usIng ono nrgumonf fho sfrIng
0ello 1orld.
Tho +rintln funcfIon doos fho ronI work In fhIs ro-
grnm. You cnn fInd ouf moro nbouf If by fyIng fho foI-
IowIng In your formInnI:
.odoc 4mt +rintln
21 Your First Program
Among ofhor fhIngs you shouId soo fhIs:
+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.
Co Is n vory woII documonfod rogrnmmIng Inngungo
buf fhIs documonfnfIon cnn bo dIffIcuIf fo undorsfnnd
unIoss you nro nIrondy fnmIIInr wIfh rogrnmmIng Inn-
gungos. ovorfhoIoss fho .odoc commnnd Is oxfromoIy
usofuI nnd n good Inco fo sfnrf whonovor you hnvo n
quosfIon.
Inck fo fho funcfIon nf hnnd, fhIs documonfnfIon Is
foIIIng you fhnf fho +rintln funcfIon wIII sond whnf-
ovor you gIvo fo If fo sfnndnrd oufuf n nnmo for fho
oufuf of fho formInnI you nro workIng In. ThIs func-
fIon Is whnf cnusos 0ello 1orld fo bo dIsInyod.
In fho noxf chnfor wo wIII oxIoro how Co sforos nnd
rorosonfs fhIngs IIko 0ello 1orld by IonrnIng nbouf
fyos.
Your First Program 22
Problems
l. Whnf Is whIfosnco
2. Whnf Is n commonf Whnf nro fho fwo wnys of
wrIfIng n commonf
3. Our rogrnm bognn wIfh pac&a.e main. Whnf
wouId fho fIIos In fho 4mt nckngo bogIn wIfh
4. Wo usod fho +rintln funcfIon dofInod In fho 4mt
nckngo. If wo wnnfod fo uso fho ;xit funcfIon
from fho os nckngo whnf wouId wo nood fo do
5. ModIfy fho rogrnm wo wrofo so fhnf Insfond of
rInfIng 0ello 1orld If rInfs 0ello< m- name
is foIIowod by your nnmo.
3 Types
In fho Insf chnfor wo usod fho dnfn fyo sfrIng fo
sforo 0ello 1orld. nfn fyos cnfogorIzo n sof of ro-
Infod vnIuos, doscrIbo fho oornfIons fhnf cnn bo dono
on fhom nnd dofIno fho wny fhoy nro sforod. SInco
fyos cnn bo n dIffIcuIf concof fo grns wo wIII Iook nf
fhom from n couIo dIfforonf orsocfIvos boforo wo
soo how fhoy nro ImIomonfod In Co.
IhIIosohors somofImos mnko n dIsfIncfIon bofwoon
fyos nnd fokons. Ior oxnmIo suoso you hnvo n dog
nnmod Mnx. Mnx Is fho fokon (n nrfIcuInr Insfnnco or
mombor) nnd dog Is fho fyo (fho gonornI concof).
og or dognoss doscrIbos n sof of roorfIos fhnf nII
dogs hnvo In common. AIfhough ovorsImIIsfIc wo
mIghf ronson IIko fhIs: AII dogs hnvo 4 Iogs, Mnx Is n
dog, fhoroforo Mnx hns 4 Iogs. Tyos In rogrnmmIng
Inngungos work In n sImIInr wny: AII sfrIngs hnvo n
Iongfh, x Is n sfrIng, fhoroforo x hns n Iongfh.
In mnfhomnfIcs wo offon fnIk nbouf sofs. Ior oxnmIo:
(fho sof of nII ronI numbors) or (fho sof of nII nnfu-
rnI numbors). Inch mombor of fhoso sofs shnros ro-
23
Types 24
orfIos wIfh nII fho ofhor mombors of fho sof. Ior oxnm-
Io nII nnfurnI numbors nro nssocInfIvo: for nII nnfu-
rnI numbors n, b, nnd c, n + (b + c) = (n + b) + c nnd n
(b c) = (n b) c. In fhIs wny sofs nro sImIInr fo
fyos In rogrnmmIng Inngungos sInco nII fho vnIuos of
n nrfIcuInr fyo shnro corfnIn roorfIos.
Co Is n sfnfIcnIIy fyod rogrnmmIng Inngungo. ThIs
monns fhnf vnrInbIos nIwnys hnvo n socIfIc fyo nnd
fhnf fyo cnnnof chnngo. SfnfIc fyIng mny soom cum-
borsomo nf fIrsf. You'II sond n Inrgo nmounf of your
fImo jusf fryIng fo fIx your rogrnm so fhnf If fInnIIy
comIIos. Iuf fyos hoI us ronson nbouf whnf our ro-
grnm Is doIng nnd cnfch n wIdo vnrIofy of common mIs-
fnkos.
Co comos wIfh sovornI buIIf-In dnfn fyos whIch wo
wIII now Iook nf In moro dofnII.
3.1 ,umbers
Co hns sovornI dIfforonf fyos fo rorosonf numbors.
ConornIIy wo sIIf numbors Info fwo dIfforonf kInds:
Infogors nnd fIonfIng-oInf numbors.
'ntegers
Infogors IIko fhoIr mnfhomnfIcnI counfornrf nro
25 Types
numbors wIfhouf n docImnI comononf. (., -3, -2, -l,
0, l, .) !nIIko fho bnso-l0 docImnI sysfom wo uso fo
rorosonf numbors, comufors uso n bnso-2 bInnry sys-
fom.
Our sysfom Is mndo u of l0 dIfforonf dIgIfs. Onco
wo'vo oxhnusfod our nvnIInbIo dIgIfs wo rorosonf
Inrgor numbors by usIng 2 (fhon 3, 4, 5, .) dIgIfs uf
noxf fo onch ofhor. Ior oxnmIo fho numbor nffor 9 Is
l0, fho numbor nffor 99 Is l00 nnd so on. Comufors
do fho snmo, buf fhoy onIy hnvo 2 dIgIfs Insfond of l0.
So counfIng Iooks IIko fhIs: 0, l, l0, ll, l00, l0l, ll0,
lll nnd so on. Tho ofhor dIfforonco bofwoon fho num-
bor sysfom wo uso nnd fho ono comufors uso Is fhnf
nII of fho Infogor fyos hnvo n dofInIfo sIzo. Thoy onIy
hnvo room for n corfnIn numbor of dIgIfs. So n 4 bIf In-
fogor mIghf Iook IIko fhIs: 0000, 000l, 00l0, 00ll,
0l00. IvonfunIIy wo run ouf of snco nnd mosf com-
ufors jusf wrn nround fo fho bogInnIng. (WhIch cnn
rosuIf In somo vory sfrnngo bohnvIor)
Co's Infogor fyos nro: uint=, uint$>, uint?, uint>@,
int=, int$>, int? nnd int>@. 8, l6, 32 nnd 64 foII us
how mnny bIfs onch of fho fyos uso. uint monns un-
sIgnod Infogor whIIo int monns sIgnod Infogor. !n-
sIgnod Infogors onIy confnIn osIfIvo numbors (or
zoro). In nddIfIon fhoro fwo nIIns fyos: b-te whIch Is
fho snmo ns uint= nnd rune whIch Is fho snmo ns
Types 26
int?. Iyfos nro nn oxfromoIy common unIf of mon-
suromonf usod on comufors (l byfo = 8 bIfs, l024
byfos = l kIIobyfo, l024 kIIobyfos = l mognbyfo, .)
nnd fhoroforo Co's b-te dnfn fyo Is offon usod In fho
dofInIfIon of ofhor fyos. Thoro nro nIso 3 mnchIno do-
ondonf Infogor fyos: uint, int nnd uintptr. Thoy nro
mnchIno doondonf bocnuso fhoIr sIzo doonds on fho
fyo of nrchIfocfuro you nro usIng.
ConornIIy If you nro workIng wIfh Infogors you shouId
jusf uso fho int fyo.
Floating Point ,umbers
IIonfIng oInf numbors nro numbors fhnf confnIn n
docImnI comononf (ronI numbors). (l.234, l23.4,
0.0000l234, l2340000) ThoIr ncfunI rorosonfnfIon on
n comufor Is fnIrIy comIIcnfod nnd nof ronIIy nocos-
snry In ordor fo know how fo uso fhom. So for now wo
nood onIy koo fho foIIowIng In mInd:
l. IIonfIng oInf numbors nro Inoxncf. OccnsIon-
nIIy If Is nof ossIbIo fo rorosonf n numbor. Ior
oxnmIo comufIng $./$ # /.AA rosuIfs In
/.///////////////$= A numbor oxfromoIy
cIoso fo whnf wo wouId oxocf, buf nof oxncfIy
fho snmo.
27 Types
2. !Iko Infogors fIonfIng oInf numbors hnvo n cor-
fnIn sIzo (32 bIf or 64 bIf). !sIng n Inrgor sIzod
fIonfIng oInf numbor Incronsos If's rocIsIon.
(how mnny dIgIfs If cnn rorosonf)
3. In nddIfIon fo numbors fhoro nro sovornI ofhor
vnIuos whIch cnn bo rorosonfod: nof n num-
bor (NaN, for fhIngs IIko ///) nnd osIfIvo nnd
nognfIvo InfInIfy. (BC nnd DC)
Co hns fwo fIonfIng oInf fyos: 4loat? nnd 4loat>@
(nIso offon roforrod fo ns sIngIo rocIsIon nnd doubIo
rocIsIon rosocfIvoIy) ns woII ns fwo nddIfIonnI fyos
for rorosonfIng comIox numbors (numbors wIfh
ImngInnry nrfs): complex>@ nnd complex$=. ConornIIy
wo shouId sfIck wIfh 4loat>@ whon workIng wIfh fIonf-
Ing oInf numbors.
3-ample
!of's wrIfo nn oxnmIo rogrnm usIng numbors. IIrsf
cronfo n foIdor cnIIod chapter? nnd mnko n main..o fIIo
confnInIng fho foIIowIng:
Types 28
pac&a.e main
import 34mt3
4unc main56 7
4mt.+rintln53$ B $ E3< $ B $6
8
If you run fho rogrnm nnd you shouId soo fhIs:
( .o run main..o
$ B $ E
ofIco fhnf fhIs rogrnm Is vory sImIInr fo fho ro-
grnm wo wrofo In chnfor 2. If confnIns fho snmo nck-
ngo IIno, fho snmo Imorf IIno, fho snmo funcfIon doc-
InrnfIon nnd usos fho snmo +rintln funcfIon. ThIs fImo
Insfond of rInfIng fho sfrIng 0ello 1orld wo rInf fho
sfrIng $ B $ E foIIowod by fho rosuIf of fho oxrossIon
$ B $. ThIs oxrossIon Is mndo u of fhroo nrfs: fho
numorIc IIfornI $ (whIch Is of fyo int), fho B oornfor
(whIch rorosonfs nddIfIon) nnd nnofhor numorIc IIf-
ornI $. !of's fry fho snmo fhIng usIng fIonfIng oInf
numbors:
4mt.+rintln53$ B $ E3< $./ B $./6
ofIco fhnf wo uso fho ./ fo foII Co fhnf fhIs Is n fIonf-
29 Types
Ing oInf numbor Insfond of nn Infogor. !unnIng fhIs
rogrnm wIII gIvo you fho snmo rosuIf ns boforo.
In nddIfIon fo nddIfIon Co hns sovornI ofhor oornfors:
B
nddIfIon
#
subfrncfIon
9
muIfIIIcnfIon
/
dIvIsIon
F
romnIndor
3.2 Strings
As wo snw In chnfor 2 n sfrIng Is n soquonco of chnr-
ncfors wIfh n dofInIfo Iongfh usod fo rorosonf foxf. Co
sfrIngs nro mndo u of IndIvIdunI byfos, usunIIy ono
for onch chnrncfor. (Chnrncfors from ofhor Inngungos
IIko ChInoso nro rorosonfod by moro fhnn ono byfo)
SfrIng IIfornIs cnn bo cronfod usIng doubIo quofos
30ello 1orld3 or bnck fIcks G0ello 1orldG. Tho dIffor-
onco bofwoon fhoso Is fhnf doubIo quofod sfrIngs cnn-
nof confnIn nowIInos nnd fhoy nIIow socInI oscno so-
quoncos. Ior oxnmIo \n gofs roIncod wIfh n nowIIno
nnd \t gofs roIncod wIfh n fnb chnrncfor.
Types 30
SovornI common oornfIons on sfrIngs IncIudo fIndIng
fho Iongfh of n sfrIng: len530ello 1orld36, nccossIng
nn IndIvIdunI chnrncfor In fho sfrIng: 30ello
1orld3H$I, nnd concnfonnfIng fwo sfrIngs fogofhor:
30ello 3 B 31orld3. !of's modIfy fho rogrnm wo cro-
nfod onrIIor fo fosf fhoso ouf:
pac&a.e main
import 34mt3
4unc main56 7
4mt.+rintln5len530ello 1orld366
4mt.+rintln530ello 1orld3H$I6
4mt.+rintln530ello 3 B 31orld36
8
A fow fhIngs fo nofIco:
l. A snco Is nIso consIdorod n chnrncfor, so fho
sfrIng's Iongfh Is ll nof l0 nnd fho 3
rd
IIno hns
30ello 3 Insfond of 30ello3.
2. SfrIngs nro Indoxod sfnrfIng nf 0 nof l. H$I
gIvos you fho 2
nd
oIomonf nof fho l
sf
. AIso nofIco
fhnf you soo $/$ Insfond of e whon you run fhIs
rogrnm. ThIs Is bocnuso fho chnrncfor Is roro-
sonfod by n byfo (romombor n byfo Is nn
Infogor).
31 Types
Ono wny fo fhInk nbouf IndoxIng wouId bo fo
show If IIko fhIs Insfond: 30ello 1orld3
$
. You'd
rond fhnf ns Tho sfrIng HoIIo WorId sub l,
Tho sfrIng HoIIo WorId nf l or Tho socond
chnrncfor of fho sfrIng HoIIo WorId.
3. ConcnfonnfIon usos fho snmo symboI ns nddI-
fIon. Tho Co comIIor fIguros ouf whnf fo do
bnsod on fho fyos of fho nrgumonfs. SInco bofh
sIdos of fho B nro sfrIngs fho comIIor nssumos
you monn concnfonnfIon nnd nof nddIfIon. (Ad-
dIfIon Is monnIngIoss for sfrIngs)
3.3 6ooleans
A booIonn vnIuo (nnmod nffor Coorgo IooIo) Is n so-
cInI l bIf Infogor fyo usod fo rorosonf fruo nnd fnIso
(or on nnd off). Throo IogIcnI oornfors nro usod wIfh
booIonn vnIuos:
JJ
nnd
KK
or
L
nof
Horo Is nn oxnmIo rogrnm showIng how fhoy cnn bo
Types 32
usod:
4unc main56 7
4mt.+rintln5true JJ true6
4mt.+rintln5true JJ 4alse6
4mt.+rintln5true KK true6
4mt.+rintln5true KK 4alse6
4mt.+rintln5Ltrue6
8
!unnIng fhIs rogrnm shouId gIvo you:
( .o run main..o
true
4alse
true
true
4alse
Wo usunIIy uso frufh fnbIos fo dofIno how fhoso oorn-
fors work:
3-pression Value
true JJ true true
true JJ 4alse 4alse
4alse JJ true 4alse
4alse JJ 4alse 4alse
33 Types
3-pression Value
true KK true true
true KK 4alse true
4alse KK true true
4alse KK 4alse 4alse
3-pression Value
Ltrue 4alse
L4alse true
Thoso nro fho sImIosf fyos IncIudod wIfh Co nnd
form fho foundnfIon from whIch nII Infor fyos nro
buIIf.
Types 34
Problems
l. How nro Infogors sforod on n comufor
2. Wo know fhnf (In bnso l0) fho Inrgosf l dIgIf
numbor Is 9 nnd fho Inrgosf 2 dIgIf numbor Is
99. CIvon fhnf In bInnry fho Inrgosf 2 dIgIf num-
bor Is ll (3), fho Inrgosf 3 dIgIf numbor Is lll
(?) nnd fho Inrgosf 4 dIgIf numbor Is llll (l5)
whnf's fho Inrgosf 8 dIgIf numbor (int: l0
l
-l =
9 nnd l0
2
-l = 99)
3. AIfhough ovoroworod for fho fnsk you cnn uso
Co ns n cnIcuInfor. WrIfo n rogrnm fhnf com-
ufos ?$?" M @@"$ nnd rInfs If fo fho for-
mInnI. (!so fho 9 oornfor for muIfIIIcnfIon)
4. Whnf Is n sfrIng How do you fInd Ifs Iongfh
5. Whnf's fho vnIuo of fho oxrossIon 5true JJ
4alse6 KK 54alse JJ true6 KK L54alse JJ
4alse6
4 Variables
! unfII now wo hnvo onIy soon rogrnms fhnf uso IIf-
ornI vnIuos (numbors, sfrIngs, ofc.) buf such rogrnms
nron'f nrfIcuInrIy usofuI. To mnko fruIy usofuI ro-
grnms wo nood fo Ionrn fwo now concofs: vnrInbIos
nnd confroI fIow sfnfomonfs. ThIs chnfor wIII oxIoro
vnrInbIos In moro dofnII.
A vnrInbIo Is n sforngo IocnfIon, wIfh n socIfIc fyo
nnd nn nssocInfod nnmo. !of's chnngo fho rogrnm wo
wrofo In chnfor 2 so fhnf If usos n vnrInbIo:
pac&a.e main
import 34mt3
4unc main56 7
var x strin. E 30ello 1orld3
4mt.+rintln5x6
8
ofIco fhnf fho sfrIng IIfornI from fho orIgInnI rogrnm
sfIII nonrs In fhIs rogrnm, buf rnfhor fhnn sond If
dIrocfIy fo fho +rintln funcfIon wo nssIgn If fo n vnrI-
35
!aria"#es 36
nbIo Insfond. VnrInbIos In Co nro cronfod by fIrsf usIng
fho var koyword, fhon socIfyIng fho vnrInbIo nnmo (x),
fho fyo (strin.) nnd fInnIIy nssIgnIng n vnIuo fo fho
vnrInbIo (0ello 1orld). Tho Insf sfo Is ofIonnI so nn
nIfornnfIvo wny of wrIfIng fho rogrnm wouId bo IIko
fhIs:
pac&a.e main
import 34mt3
4unc main56 7
var x strin.
x E 30ello 1orld3
4mt.+rintln5x6
8
VnrInbIos In Co nro sImIInr fo vnrInbIos In nIgobrn buf
fhoro nro somo subfIo dIfforoncos:
IIrsf whon wo soo fho E symboI wo hnvo n fondoncy fo
rond fhnf ns x oqunIs fho sfrIng HoIIo WorId. Thoro's
nofhIng wrong wIfh rondIng our rogrnm fhnf wny, buf
If's boffor fo rond If ns x fnkos fho sfrIng HoIIo WorId
or x Is nssIgnod fho sfrIng HoIIo WorId. ThIs dIsfInc-
fIon Is Imorfnnf bocnuso (ns fhoIr nnmo wouId sug-
gosf) vnrInbIos cnn chnngo fhoIr vnIuo fhroughouf fho
IIfofImo of n rogrnm. Try runnIng fho foIIowIng:
37 !aria"#es
pac&a.e main
import 34mt3
4unc main56 7
var x strin.
x E 34irst3
4mt.+rintln5x6
x E 3second3
4mt.+rintln5x6
8
In fncf you cnn ovon do fhIs:
var x strin.
x E 34irst 3
4mt.+rintln5x6
x E x B 3second3
4mt.+rintln5x6
ThIs rogrnm wouId bo nonsonso If you rond If IIko nn
nIgobrnIc fhoorom. Iuf If mnkos sonso If you nro cnro-
fuI fo rond fho rogrnm ns n IIsf of commnnds. Whon
wo soo x E x B 3second3 wo shouId rond If ns nssIgn
fho concnfonnfIon of fho vnIuo of fho vnrInbIo x nnd fho
sfrIng IIfornI socond fo fho vnrInbIo x. Tho rIghf sIdo
of fho E Is dono fIrsf nnd fho rosuIf Is fhon nssIgnod fo
fho Ioff sIdo of fho E.
Tho x E x B - form Is so common In rogrnmmIng fhnf
!aria"#es 38
Co hns n socInI nssIgnmonf sfnfomonf: BE. Wo couId
hnvo wrIffon x E x B 3second3 ns x BE 3second3 nnd If
wouId hnvo dono fho snmo fhIng. (Ofhor oornfors cnn
bo usod fho snmo wny)
Anofhor dIfforonco bofwoon Co nnd nIgobrn Is fhnf wo
uso n dIfforonf symboI for oqunIIfy: EE. (Two oqunI
sIgns noxf fo onch ofhor) EE Is nn oornfor IIko B nnd If
rofurns n booIonn. Ior oxnmIo:
var x strin. E 3hello3
var - strin. E 3)orld3
4mt.+rintln5x EE -6
ThIs rogrnm shouId rInf 4alse bocnuso hello Is nof
fho snmo ns )orld. On fho ofhor hnnd:
var x strin. E 3hello3
var - strin. E 3hello3
4mt.+rintln5x EE -6
ThIs wIII rInf true bocnuso fho fwo sfrIngs nro fho
snmo.
SInco cronfIng n now vnrInbIo wIfh n sfnrfIng vnIuo Is
so common Co nIso suorfs n shorfor sfnfomonf:
39 !aria"#es
x :E 30ello 1orld3
ofIco fho : boforo fho E nnd fhnf no fyo wns socI-
fIod. Tho fyo Is nof nocossnry bocnuso fho Co comIIor
Is nbIo fo Infor fho fyo bnsod on fho IIfornI vnIuo you
nssIgn fho vnrInbIo. (SInco you nro nssIgnIng n sfrIng
IIfornI, x Is gIvon fho fyo strin.) Tho comIIor cnn
nIso do Inforonco wIfh fho var sfnfomonf:
var x E 30ello 1orld3
Tho snmo fhIng works for ofhor fyos:
x :E "
4mt.+rintln5x6
ConornIIy you shouId uso fhIs shorfor form whonovor
ossIbIo.
4.1 4o0 to ,ame a Variable
nmIng n vnrInbIo roorIy Is nn Imorfnnf nrf of
soffwnro dovoIomonf. nmos musf sfnrf wIfh n Ioffor
nnd mny confnIn Ioffors, numbors or fho N (undorscoro)
symboI. Tho Co comIIor doosn'f cnro whnf you nnmo n
vnrInbIo so fho nnmo Is monnf for your (nnd ofhors)
!aria"#es 40
bonofIf. IIck nnmos whIch cIonrIy doscrIbo fho vnrI-
nbIo's uroso. Suoso wo hnd fho foIIowIng:
x :E 3*ax3
4mt.+rintln53*- do.Os name is3< x6
In fhIs cnso x Is nof n vory good nnmo for n vnrInbIo. A
boffor nnmo wouId bo:
name :E 3*ax3
4mt.+rintln53*- do.Os name is3< name6
or ovon:
do.sName :E 3*ax3
4mt.+rintln53*- do.Os name is3< do.sName6
In fhIs Insf cnso wo uso n socInI wny fo rorosonf muI-
fIIo words In n vnrInbIo nnmo known ns Iowor cnmoI
cnso (nIso know ns mIxod cnso, bumy cns, cnmoI
bnck or hum bnck). Tho fIrsf Ioffor of fho fIrsf word Is
Ioworcnso, fho fIrsf Ioffor of fho subsoquonf words Is
uorcnso nnd nII fho ofhor Ioffors nro Ioworcnso.
4.2 Scope
CoIng bnck fo fho rogrnm wo snw nf fho bogInnIng of
41 !aria"#es
fho chnfor:
pac&a.e main
import 34mt3
4unc main56 7
var x strin. E 30ello 1orld3
4mt.+rintln5x6
8
Anofhor wny of wrIfIng fhIs rogrnm wouId bo IIko
fhIs:
pac&a.e main
import 34mt3
var x strin. E 30ello 1orld3
4unc main56 7
4mt.+rintln5x6
8
ofIco fhnf wo movod fho vnrInbIo oufsIdo of fho mnIn
funcfIon. ThIs monns fhnf ofhor funcfIons cnn nccoss
fhIs vnrInbIo:
!aria"#es 42
var x strin. E 30ello 1orld3
4unc main56 7
4mt.+rintln5x6
8
4unc 456 7
4mt.+rintln5x6
8
Tho 4 funcfIon now hns nccoss fo fho x vnrInbIo. ow
suoso fhnf wo wrofo fhIs Insfond:
4unc main56 7
var x strin. E 30ello 1orld3
4mt.+rintln5x6
8
4unc 456 7
4mt.+rintln5x6
8
If you run fhIs rogrnm you shouId soo nn orror:
.\main..o:$$: unde4ined: x
Tho comIIor Is foIIIng you fhnf fho x vnrInbIo InsIdo of
fho 4 funcfIon doosn'f oxIsf. If onIy oxIsfs InsIdo of fho
main funcfIon. Tho rnngo of Incos whoro you nro nI-
Iowod fo uso x Is cnIIod fho s$ope of fho vnrInbIo. Ac-
43 !aria"#es
cordIng fo fho Inngungo socIfIcnfIon Co Is IoxIcnIIy
scood usIng bIocks. InsIcnIIy fhIs monns fhnf fho
vnrInbIo oxIsfs wIfhIn fho nonrosf curIy brncos 7 8 (n
bIock) IncIudIng nny nosfod curIy brncos (bIocks), buf
nof oufsIdo of fhom. Scoo cnn bo n IIffIo confusIng nf
fIrsf; ns wo soo moro Co oxnmIos If shouId bocomo
moro cIonr.
4.3 Constants
Co nIso hns suorf for consfnnfs. Consfnnfs nro bnsI-
cnIIy vnrInbIos whoso vnIuos cnnnof bo chnngod Infor.
Thoy nro cronfod In fho snmo wny you cronfo vnrInbIos
buf Insfond of usIng fho var koyword wo uso fho const
koyword:
pac&a.e main
import 34mt3
4unc main56 7
const x strin. E 30ello 1orld3
4mt.+rintln5x6
8
ThIs:
!aria"#es 44
const x strin. E 30ello 1orld3
x E 3Some other strin.3
!osuIfs In n comIIo-fImo orror:
.\main..o:P: cannot assi.n to x
Consfnnfs nro n good wny fo rouso common vnIuos In n
rogrnm wIfhouf wrIfIng fhom ouf onch fImo. Ior ox-
nmIo +i In fho math nckngo Is dofInod ns n consfnnf.
4.4 7e(ining $ultiple Variables
Co nIso hns nnofhor shorfhnnd whon you nood fo do-
fIno muIfIIo vnrInbIos:
var 5
a E "
b E $/
c E $"
6
!so fho koyword var (or const) foIIowod by nronfho-
sos wIfh onch vnrInbIo on Ifs own IIno.
45 !aria"#es
4.5 "n 3-ample Program
Horo's nn oxnmIo rogrnm whIch fnkos In n numbor
onforod by fho usor nnd doubIos If:
pac&a.e main
import 34mt3
4unc main56 7
4mt.+rint53;nter a number: 36
var input 4loat>@
4mt.Scan453F43< Jinput6
output :E input 9
4mt.+rintln5output6
8
Wo uso nnofhor funcfIon from fho 4mt nckngo fo rond
fho usor Inuf (Scan4). Jinput wIII bo oxInInod In n
Infor chnfor, for now nII wo nood fo know Is fhnf Scan4
fIIIs Inuf wIfh fho numbor wo onfor.
!aria"#es 46
Problems
l. Whnf nro fwo wnys fo cronfo n now vnrInbIo
2. Whnf Is fho vnIuo of x nffor runnIng:
x :E "Q x BE $
3. Whnf Is scoo nnd how do you doformIno fho
scoo of n vnrInbIo In Co
4. Whnf Is fho dIfforonco bofwoon var nnd const
5. !sIng fho oxnmIo rogrnm ns n sfnrfIng oInf,
wrIfo n rogrnm fhnf convorfs from InhronhoIf
Info CoIsIus. (C E 5! # ?6 9 "/A)
6. WrIfo nnofhor rogrnm fhnf convorfs from foof
Info mofors. ($ 4t E /.?/@= m)
5 Control Structures
ow fhnf wo know how fo uso vnrInbIos If's fImo fo
sfnrf wrIfIng somo usofuI rogrnms. IIrsf Iof's wrIfo n
rogrnm fhnf counfs fo l0, sfnrfIng from l, wIfh onch
numbor on Ifs own IIno. !sIng whnf wo'vo Ionrnod so
fnr wo couId wrIfo fhIs:
pac&a.e main
import 34mt3
4unc main56 7
4mt.+rintln5$6
4mt.+rintln56
4mt.+rintln5?6
4mt.+rintln5@6
4mt.+rintln5"6
4mt.+rintln5>6
4mt.+rintln5P6
4mt.+rintln5=6
4mt.+rintln5A6
4mt.+rintln5$/6
8
Or fhIs:
47
%ontro# Stru$tures 48
pac&a.e main
import 34mt3
4unc main56 7
4mt.+rintln5G$

?
@
"
>
P
=
A
$/G6
8
Iuf bofh of fhoso rogrnms nro roffy fodIous fo wrIfo.
Whnf wo nood Is n wny of doIng somofhIng muIfIIo
fImos.
5.1 For
Tho 4or sfnfomonf nIIows us fo roonf n IIsf of sfnfo-
monfs (n bIock) muIfIIo fImos. !owrIfIng our rovIous
rogrnm usIng n 4or sfnfomonf Iooks IIko fhIs:
49 %ontro# Stru$tures
pac&a.e main
import 34mt3
4unc main56 7
i :E $
4or i RE $/ 7
4mt.+rintln5i6
i E i B $
8
8
IIrsf wo cronfo n vnrInbIo cnIIod i fhnf wo uso fo sforo
fho numbor wo wnnf fo rInf. Thon wo cronfo n 4or
Ioo by usIng fho koyword 4or, rovIdIng n condIfIonnI
oxrossIon whIch Is oIfhor true or 4alse nnd fInnIIy
suIyIng n bIock fo oxocufo. Tho for Ioo works IIko
fhIs:
l. Wo ovnIunfo (run) fho oxrossIon i RE $/ (I Ioss
fhnn or oqunI fo l0). If fhIs ovnIunfos fo fruo
fhon wo run fho sfnfomonfs InsIdo of fho bIock.
OfhorwIso wo jum fo fho noxf IIno of our ro-
grnm nffor fho bIock. (In fhIs cnso fhoro Is nofh-
Ing nffor fho for Ioo so wo oxIf fho rogrnm)
2. Affor wo run fho sfnfomonfs InsIdo of fho bIock
wo Ioo bnck fo fho bogInnIng of fho for sfnfo-
monf nnd roonf sfo l.
%ontro# Stru$tures 50
Tho i E i B $ IIno Is oxfromoIy Imorfnnf, bocnuso
wIfhouf If i RE $/ wouId nIwnys ovnIunfo fo true nnd
our rogrnm wouId novor sfo. (Whon fhIs hnons
fhIs Is roforrod fo ns nn InfInIfo Ioo)
As nn oxorcIso Iofs wnIk fhrough fho rogrnm IIko n
comufor wouId:
Cronfo n vnrInbIo nnmod i wIfh fho vnIuo l
Is i RE $/ Yos.
IrInf i
Sof i fo i B $ (i now oqunIs 2)
Is i RE $/ Yos.
IrInf i
Sof i fo i B $ (i now oqunIs 3)
.
Sof i fo i B $ (i now oqunIs ll)
Is i RE $/ o.
ofhIng Ioff fo do, so oxIf
Ofhor rogrnmmIng Inngungos hnvo n Iof of dIfforonf
fyos of Ioos (whIIo, do, unfII, foronch, .) buf Co onIy
hns ono fhnf cnn bo usod In n vnrIofy of dIfforonf wnys.
Tho rovIous rogrnm couId nIso hnvo boon wrIffon
IIko fhIs:
51 %ontro# Stru$tures
4unc main56 7
4or i :E $Q i RE $/Q iBB 7
4mt.+rintln5i6
8
8
ow fho condIfIonnI oxrossIon nIso confnIns fwo ofhor
sfnfomonfs wIfh somIcoIons bofwoon fhom. IIrsf wo
hnvo fho vnrInbIo InIfInIIznfIon, fhon wo hnvo fho con-
dIfIon fo chock onch fImo nnd fInnIIy wo Incromonf
fho vnrInbIo. (nddIng l fo n vnrInbIo Is so common fhnf
wo hnvo n socInI oornfor: BB. SImIInrIy subfrncfIng l
cnn bo dono wIfh ##)
Wo wIII soo nddIfIonnI wnys of usIng fho for Ioo In
Infor chnfors.
5.2 '(
!of's modIfy fho rogrnm wo jusf wrofo so fhnf Insfond
of jusf rInfIng fho numbors l-l0 on onch IIno If nIso
socIfIos whofhor or nof fho numbor Is ovon or odd.
!Iko fhIs:
%ontro# Stru$tures 52
$ odd
even
? odd
@ even
" odd
> even
P odd
= even
A odd
$/ even
IIrsf wo nood n wny of doformInIng whofhor or nof n
numbor Is ovon or odd. An onsy wny fo foII Is fo dIvIdo
fho numbor by 2. If you hnvo nofhIng Ioff ovor fhon fho
numbor Is ovon, ofhorwIso If's odd. So how do wo fInd
fho romnIndor nffor dIvIsIon In Co Wo uso fho F oor-
nfor. $ F oqunIs $, F oqunIs /, ? F oqunIs $ nnd
so on.
oxf wo nood n wny of choosIng fo do dIfforonf fhIngs
bnsod on n condIfIon. Ior fhnf wo uso fho i4 sfnfo-
monf:
i4 i F EE / 7
// even
8 else 7
// odd
8
An i4 sfnfomonf Is sImIInr fo n 4or sfnfomonf In fhnf If
53 %ontro# Stru$tures
hns n condIfIon foIIowod by n bIock. If sfnfomonfs nIso
hnvo nn ofIonnI else nrf. If fho condIfIon ovnIunfos
fo true fhon fho bIock nffor fho condIfIon Is run, ofhor-
wIso oIfhor fho bIock Is skIod or If fho else bIock Is
rosonf fhnf bIock Is run.
If sfnfomonfs cnn nIso hnvo else i4 nrfs:
i4 i F EE / 7
// divisible b-
8 else i4 i F ? EE / 7
// divisible b- ?
8 else i4 i F @ EE / 7
// divisible b- @
8
Tho condIfIons nro chockod fo down nnd fho fIrsf ono
fo rosuIf In fruo wIII hnvo Ifs nssocInfod bIock oxo-
cufod. ono of fho ofhor bIocks wIII oxocufo, ovon If
fhoIr condIfIons nIso nss. (So for oxnmIo fho numbor
8 Is dIvIsIbIo by bofh 4 nnd 2, buf fho // divisible b-
@ bIock wIII novor oxocufo bocnuso fho // divisible b-
bIock Is dono fIrsf)
IuffIng If nII fogofhor wo hnvo:
%ontro# Stru$tures 54
4unc main56 7
4or i :E $Q i RE $/Q iBB 7
i4 i F EE / 7
4mt.+rintln5i< 3even36
8 else 7
4mt.+rintln5i< 3odd36
8
8
8
!of's wnIk fhrough fhIs rogrnm:
Cronfo n vnrInbIo i of fyo int nnd gIvo If fho vnIuo $
Is i Ioss fhnn or oqunI fo $/ Yos: jum fo fho bIock
Is fho romnIndor of i oqunI fo / o: jum fo fho
else bIock
IrInf i foIIowod by odd
Incromonf i (fho sfnfomonf nffor fho condIfIon)
Is i Ioss fhnn or oqunI fo $/ Yos: jum fo fho bIock
Is fho romnIndor of i oqunI fo / Yos: jum fo fho
i4 bIock
IrInf i foIIowod by even
.
Tho romnIndor oornfor, whIIo rnroIy soon oufsIdo of
oIomonfnry schooI, furns ouf fo bo ronIIy usofuI whon
rogrnmmIng. You'II soo If furn u ovorywhoro from
zobrn sfrIIng fnbIos fo nrfIfIonIng dnfn sofs.
55 %ontro# Stru$tures
5.3 S0itc+
Suoso wo wnnfod fo wrIfo n rogrnm fhnf rInfod
fho IngIIsh nnmos for numbors. !sIng whnf wo'vo
Ionrnod so fnr wo mIghf sfnrf by doIng fhIs:
i4 i EE / 7
4mt.+rintln53Sero36
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
SInco wrIfIng n rogrnm In fhIs wny wouId bo roffy
fodIous Co rovIdos nnofhor sfnfomonf fo mnko fhIs
onsIor: fho s)itch sfnfomonf. Wo cnn rowrIfo our ro-
grnm fo Iook IIko fhIs:
%ontro# Stru$tures 56
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
A swIfch sfnfomonf sfnrfs wIfh fho koyword s)itch foI-
Iowod by nn oxrossIon (In fhIs cnso i) nnd fhon n so-
rIos of cases. Tho vnIuo of fho oxrossIon Is comnrod
fo fho oxrossIon foIIowIng onch case koyword. If fhoy
nro oquIvnIonf fhon fho sfnfomonf(s) foIIowIng fho : Is
oxocufod.
!Iko nn If sfnfomonf onch cnso Is chockod fo down
nnd fho fIrsf ono fo succood Is choson. A swIfch nIso
suorfs n dofnuIf cnso whIch wIII hnon If nono of
fho cnsos mnfchos fho vnIuo. (KInd of IIko fho oIso In
nn If sfnfomonf)
Thoso nro fho mnIn confroI fIow sfnfomonfs. AddIfIonnI
sfnfomonfs wIII bo oxIorod In Infor chnfors.
57 %ontro# Stru$tures
Problems
l. Whnf doos fho foIIowIng rogrnm rInf:
i :E $/
i4 i > $/ 7
4mt.+rintln53Bi.36
8 else 7
4mt.+rintln53Small36
8
2. WrIfo n rogrnm fhnf rInfs ouf nII fho numbors
ovonIy dIvIsIbIo by 3 bofwoon l nnd l00. (3, 6, 9,
ofc.)
3. WrIfo n rogrnm fhnf rInfs fho numbors from l
fo l00. Iuf for muIfIIos of fhroo rInf "IIzz" In-
sfond of fho numbor nnd for fho muIfIIos of fIvo
rInf "Iuzz". Ior numbors whIch nro muIfIIos
of bofh fhroo nnd fIvo rInf "IIzzIuzz".
! "rrays# Slices and $aps
In chnfor 3 wo Ionrnod nbouf Co's bnsIc fyos. In fhIs
chnfor wo wIII Iook nf fhroo moro buIIf-In fyos: nr-
rnys, sIIcos nnd mns.
!.1 "rrays
An nrrny Is n numborod soquonco of oIomonfs of n sIn-
gIo fyo wIfh n fIxod Iongfh. In Co fhoy Iook IIko fhIs:
var x H"Iint
x Is nn oxnmIo of nn nrrny whIch Is comosod of 5
ints. Try runnIng fho foIIowIng rogrnm:
58
59 &rrays' S#i$es and (aps
pac&a.e main
import 34mt3
4unc main56 7
var x H"Iint
xH@I E $//
4mt.+rintln5x6
8
You shouId soo fhIs:
H/ / / / $//I
xH@I E $// shouId bo rond sof fho 5
fh
oIomonf of fho
nrrny x fo l00. If mIghf soom sfrnngo fhnf xH@I roro-
sonfs fho 5
fh
oIomonf Insfond of fho 4
fh
buf IIko sfrIngs,
nrrnys nro Indoxod sfnrfIng from 0. Arrnys nro nc-
cossod In n sImIInr wny. Wo couId chnngo
4mt.+rintln5x6 fo 4mt.+rintln5xH@I6 nnd wo wouId gof
l00.
Horo's nn oxnmIo rogrnm fhnf usos nrrnys:
&rrays' S#i$es and (aps 60
4unc main56 7
var x H"I4loat>@
xH/I E A=
xH$I E A?
xHI E PP
xH?I E =
xH@I E =?
var total 4loat>@ E /
4or i :E /Q i R "Q iBB 7
total BE xHiI
8
4mt.+rintln5total / "6
8
ThIs rogrnm comufos fho nvorngo of n sorIos of fosf
scoros. If you run If you shouId soo =>.>. !of's wnIk
fhrough fho rogrnm:
IIrsf wo cronfo nn nrrny of Iongfh 5 fo hoId our fosf
scoros, fhon wo fIII u onch oIomonf wIfh n grndo
oxf wo sofu n for Ioo fo comufo fho fofnI scoro
IInnIIy wo dIvIdo fho fofnI scoro by fho numbor of oI-
omonfs fo fInd fho nvorngo
ThIs rogrnm works, buf Co rovIdos somo fonfuros wo
cnn uso fo Imrovo If. IIrsf fhoso 2 nrfs: i R " nnd
total / " shouId fhrow u n rod fIng for us. Sny wo
61 &rrays' S#i$es and (aps
chnngod fho numbor of grndos from 5 fo 6. Wo wouId
nIso nood fo chnngo bofh of fhoso nrfs. If wouId bo
boffor fo uso fho Iongfh of fho nrrny Insfond:
var total 4loat>@ E /
4or i :E /Q i R len5x6Q iBB 7
total BE xHiI
8
4mt.+rintln5total / len5x66
Co nhond nnd mnko fhoso chnngos nnd run fho ro-
grnm. You shouId gof nn orror:
( .o run tmp..o
V command#line#ar.uments
.\tmp..o:$A: invalid operation: total / "
5mismatched t-pes 4loat>@ and int6
Tho Issuo horo Is fhnf len5x6 nnd total hnvo dIfforonf
fyos. total Is n 4loat>@ whIIo len5x6 Is nn int. So wo
nood fo convorf len5x6 Info n 4loat>@:
4mt.+rintln5total / 4loat>@5len5x666
ThIs Is nn oxnmIo of n fyo convorsIon. In gonornI fo
convorf bofwoon fyos you uso fho fyo nnmo IIko n
funcfIon.
&rrays' S#i$es and (aps 62
Anofhor chnngo fo fho rogrnm wo cnn mnko Is fo uso
n socInI form of fho for Ioo:
var total 4loat>@ E /
4or i< value :E ran.e x 7
total BE value
8
4mt.+rintln5total / 4loat>@5len5x666
In fhIs for Ioo i rorosonfs fho curronf osIfIon In fho
nrrny nnd value Is fho snmo ns xHiI. Wo uso fho koy-
word ran.e foIIowod by fho nnmo of fho vnrInbIo wo
wnnf fo Ioo ovor.
!unnIng fhIs rogrnm wIII rosuIf In nnofhor orror:
( .o run tmp..o
V command#line#ar.uments
.\tmp..o:$>: i declared and not used
Tho Co comIIor won'f nIIow you fo cronfo vnrInbIos
fhnf you novor uso. SInco wo don'f uso i InsIdo of our
Ioo wo nood fo chnngo If fo fhIs:
63 &rrays' S#i$es and (aps
var total 4loat>@ E /
4or N< value :E ran.e x 7
total BE value
8
4mt.+rintln5total / 4loat>@5len5x666
A sIngIo N (undorscoro) Is usod fo foII fho comIIor fhnf
wo don'f nood fhIs. (In fhIs cnso wo don'f nood fho Ifor-
nfor vnrInbIo)
Co nIso rovIdos n shorfor synfnx for cronfIng nrrnys:
x :E H"I4loat>@7 A=< A?< PP< =< =? 8
Wo no Iongor nood fo socIfy fho fyo bocnuso Co cnn
fIguro If ouf. SomofImos nrrnys IIko fhIs cnn gof foo
Iong fo fIf on ono IIno, so Co nIIows you fo bronk If u
IIko fhIs:
x :E H"I4loat>@7
A=<
A?<
PP<
=<
=?<
8
ofIco fho oxfrn frnIIIng < nffor =?. ThIs Is roquIrod by
&rrays' S#i$es and (aps 64
Co nnd If nIIows us fo onsIIy romovo nn oIomonf from
fho nrrny by commonfIng ouf fho IIno:
x :E H@I4loat>@7
A=<
A?<
PP<
=<
// =?<
8
ThIs oxnmIo IIIusfrnfos n mnjor Issuo wIfh nrrnys:
fhoIr Iongfh Is fIxod nnd nrf of fho nrrny's fyo nnmo.
In ordor fo romovo fho Insf Ifom, wo ncfunIIy hnd fo
chnngo fho fyo ns woII. Co's soIufIon fo fhIs robIom
Is fo uso n dIfforonf fyo: sIIcos.
!.2 Slices
A sIIco Is n sogmonf of nn nrrny. !Iko nrrnys sIIcos nro
IndoxnbIo nnd hnvo n Iongfh. !nIIko nrrnys fhIs Iongfh
Is nIIowod fo chnngo. Horo's nn oxnmIo of n sIIco:
var x HI4loat>@
Tho onIy dIfforonco bofwoon fhIs nnd nn nrrny Is fho
mIssIng Iongfh bofwoon fho brnckofs. In fhIs cnso x
hns boon cronfod wIfh n Iongfh of /.
65 &rrays' S#i$es and (aps
If you wnnf fo cronfo n sIIco you shouId uso fho buIIf-In
ma&e funcfIon:
x :E ma&e5HI4loat>@< "6
ThIs cronfos n sIIco fhnf Is nssocInfod wIfh nn undorIy-
Ing 4loat>@ nrrny of Iongfh 5. SIIcos nro nIwnys nssocI-
nfod wIfh somo nrrny, nnd nIfhough fhoy cnn novor bo
Iongor fhnn fho nrrny, fhoy cnn bo smnIIor. Tho ma&e
funcfIon nIso nIIows n 3
rd
nrnmofor:
x :E ma&e5HI4loat>@< "< $/6
l0 rorosonfs fho cnncIfy of fho undorIyIng nrrny
whIch fho sIIco oInfs fo:
Anofhor wny fo cronfo sIIcos Is fo uso fho Hlo) : hi.hI
oxrossIon:
arr :E HI4loat>@7$<<?<@<"8
x :E arrH/:"I
&rrays' S#i$es and (aps 66
lo) Is fho Indox of whoro fo sfnrf fho sIIco nnd hi.h Is
fho Indox whoro fo ond If (buf nof IncIudIng fho Indox
IfsoIf). Ior oxnmIo whIIo arrH/:"I rofurns
H$<<?<@<"I, arrH$:@I rofurns H<?<@I.
Ior convonIonco wo nro nIso nIIowod fo omIf lo), hi.h
or ovon bofh lo) nnd hi.h. arrH/:I Is fho snmo ns
arrH/:len5arr6I, arrH:"I Is fho snmo ns arrH/:"I nnd
arrH:I Is fho snmo ns arrH/:len5arr6I.
Slice Functions
Co IncIudos fwo buIIf-In funcfIons fo nssIsf wIfh sIIcos:
append nnd cop-. Horo Is nn oxnmIo of append:
4unc main56 7
slice$ :E HIint7$<<?8
slice :E append5slice$< @< "6
4mt.+rintln5slice$< slice6
8
Affor runnIng fhIs rogrnm slice$ hns H$<<?I nnd
slice hns H$<<?<@<"I. append cronfos n now sIIco by
fnkIng nn oxIsfIng sIIco (fho fIrsf nrgumonf) nnd n-
ondIng nII fho foIIowIng nrgumonfs fo If.
Horo Is nn oxnmIo of coy:
67 &rrays' S#i$es and (aps
4unc main56 7
slice$ :E HIint7$<<?8
slice :E ma&e5HIint< 6
cop-5slice< slice$6
4mt.+rintln5slice$< slice6
8
Affor runnIng fhIs rogrnm slice$ hns H$<<?I nnd
slice hns H$<I. Tho confonfs of slice$ nro coIod
Info slice, buf sInco slice hns room for onIy fwo oIo-
monfs onIy fho fIrsf fwo oIomonfs of slice$ nro coIod.
!.3 $aps
A mn Is nn unordorod coIIocfIon of koy-vnIuo nIrs.
AIso known ns nn nssocInfIvo nrrny, n hnsh fnbIo or n
dIcfIonnry, mns nro usod fo Iook u n vnIuo by Ifs ns-
socInfod koy. Horo's nn oxnmIo of n mn In Co:
var x mapHstrin.Iint
Tho mn fyo Is rorosonfod by fho koyword map, foI-
Iowod by fho koy fyo In brnckofs nnd fInnIIy fho vnIuo
fyo. If you woro fo rond fhIs ouf Ioud you wouId sny x
Is n mn of strin.s fo ints.
!Iko nrrnys nnd sIIcos mns cnn bo nccossod usIng
brnckofs. Try runnIng fho foIIowIng rogrnm:
&rrays' S#i$es and (aps 68
var x mapHstrin.Iint
xH3&e-3I E $/
4mt.+rintln5x6
You shouId soo nn orror sImIInr fo fhIs:
panic: runtime error: assi.nment to entr- in nil
map
.oroutine $ Hrunnin.I:
main.main56
main..o:P B/x@d
.oroutine Hs-scallI:
created b- runtime.main

C:/Users/W%*:N:'$/Wpp%ata/,ocal/Uemp//bindi
t>A@AP$P//.o/src/p&./runtime/proc.c:$
exit status
! fIII now wo hnvo onIy soon comIIo-fImo orrors.
ThIs Is nn oxnmIo of n runfImo orror. As fho nnmo
wouId ImIy, runfImo orrors hnon whon you run fho
rogrnm, whIIo comIIo-fImo orrors hnon whon you
fry fo comIIo fho rogrnm.
Tho robIom wIfh our rogrnm Is fhnf mns hnvo fo bo
InIfInIIzod boforo fhoy cnn bo usod. Wo shouId hnvo
wrIffon fhIs:
69 &rrays' S#i$es and (aps
x :E ma&e5mapHstrin.Iint6
xH3&e-3I E $/
4mt.+rintln5xH3&e-3I6
If you run fhIs rogrnm you shouId soo $/ dIsInyod.
Tho sfnfomonf xH3&e-3I E $/ Is sImIInr fo whnf wo
snw wIfh nrrnys buf fho koy, Insfond of boIng nn Info-
gor, Is n sfrIng bocnuso fho mn's koy fyo Is strin..
Wo cnn nIso cronfo mns wIfh n koy fyo of int:
x :E ma&e5mapHintIint6
xH$I E $/
4mt.+rintln5xH$I6
ThIs Iooks vory much IIko nn nrrny buf fhoro nro n fow
dIfforoncos. IIrsf fho Iongfh of n mn (found by doIng
len5x6) cnn chnngo ns wo ndd now Ifoms fo If. Whon
fIrsf cronfod If hns n Iongfh of 0, nffor xH$I E $/ If hns
n Iongfh of l. Socond mns nro nof soquonfInI. Wo hnvo
xH$I, nnd wIfh nn nrrny fhnf wouId ImIy fhoro musf
bo nn xH/I, buf mns don'f hnvo fhIs roquIromonf.
Wo cnn nIso doIofo Ifoms from n mn usIng fho buIIf-In
delete funcfIon:
delete5x< $6
&rrays' S#i$es and (aps 70
!of's Iook nf nn oxnmIo rogrnm fhnf usos n mn:
pac&a.e main
import 34mt3
4unc main56 7
elements :E ma&e5mapHstrin.Istrin.6
elementsH303I E 30-dro.en3
elementsH30e3I E 30elium3
elementsH3,i3I E 3,ithium3
elementsH3Be3I E 3Ber-llium3
elementsH3B3I E 3Boron3
elementsH3C3I E 3Carbon3
elementsH3N3I E 3Nitro.en3
elementsH3T3I E 3Tx-.en3
elementsH3!3I E 3!luorine3
elementsH3Ne3I E 3Neon3
4mt.+rintln5elementsH3,i3I6
8
elements Is n mn fhnf rorosonfs fho fIrsf l0 chomIcnI
oIomonfs Indoxod by fhoIr symboI. ThIs Is n vory com-
mon wny of usIng mns: ns n Iooku fnbIo or n dIcfIo-
nnry. Suoso wo frIod fo Iook u nn oIomonf fhnf
doosn'f oxIsf:
4mt.+rintln5elementsH3Un3I6
If you run fhIs you shouId soo nofhIng rofurnod. Toch-
71 &rrays' S#i$es and (aps
nIcnIIy n mn rofurns fho zoro vnIuo for fho vnIuo fyo
(whIch for sfrIngs Is fho omfy sfrIng). AIfhough wo
couId chock for fho zoro vnIuo In n condIfIon
(elementsH3Un3I EE 33) Co rovIdos n boffor wny:
name< o& :E elementsH3Un3I
4mt.+rintln5name< o&6
AccossIng nn oIomonf of n mn cnn rofurn fwo vnIuos
Insfond of jusf ono. Tho fIrsf vnIuo Is fho rosuIf of fho
Iooku, fho socond foIIs us whofhor or nof fho Iooku
wns succossfuI. In Co wo offon soo codo IIko fhIs:
i4 name< o& :E elementsH3Un3IQ o& 7
4mt.+rintln5name< o&6
8
IIrsf wo fry fo gof fho vnIuo from fho mn, fhon If If's
succossfuI wo run fho codo InsIdo of fho bIock.
!Iko wo snw wIfh nrrnys fhoro Is nIso n shorfor wny fo
cronfo mns:
&rrays' S#i$es and (aps 72
elements :E mapHstrin.Istrin.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
Mns nro nIso offon usod fo sforo gonornI InformnfIon.
!of's modIfy our rogrnm so fhnf Insfond of jusf sfor-
Ing fho nnmo of fho oIomonf wo sforo Ifs sfnndnrd
sfnfo (sfnfo nf room fomornfuro) ns woII:
4unc main56 7
elements :E mapHstrin.ImapHstrin.Istrin.7
303: mapHstrin.Istrin.7
3name3:30-dro.en3<
3state3:3.as3<
8<
30e3: mapHstrin.Istrin.7
3name3:30elium3<
3state3:3.as3<
8<
3,i3: mapHstrin.Istrin.7
3name3:3,ithium3<
3state3:3solid3<
8<
73 &rrays' S#i$es and (aps
3Be3: mapHstrin.Istrin.7
3name3:3Ber-llium3<
3state3:3solid3<
8<
3B3: mapHstrin.Istrin.7
3name3:3Boron3<
3state3:3solid3<
8<
3C3: mapHstrin.Istrin.7
3name3:3Carbon3<
3state3:3solid3<
8<
3N3: mapHstrin.Istrin.7
3name3:3Nitro.en3<
3state3:3.as3<
8<
3T3: mapHstrin.Istrin.7
3name3:3Tx-.en3<
3state3:3.as3<
8<
3!3: mapHstrin.Istrin.7
3name3:3!luorine3<
3state3:3.as3<
8<
3Ne3: mapHstrin.Istrin.7
3name3:3Neon3<
3state3:3.as3<
8<
8
i4 el< o& :E elementsH3,i3IQ o& 7
4mt.+rintln5elH3name3I< elH3state3I6
8
8
ofIco fhnf fho fyo of our mn hns chnngod from
&rrays' S#i$es and (aps 74
mapHstrin.Istrin. fo mapHstrin.ImapHstrin.Istrin..
Wo now hnvo n mn of sfrIngs fo mns of sfrIngs fo
sfrIngs. Tho oufor mn Is usod ns n Iooku fnbIo bnsod
on fho oIomonf's symboI, whIIo fho Innor mns nro
usod fo sforo gonornI InformnfIon nbouf fho oIomonfs.
AIfhough mns nro offon usod IIko fhIs, In chnfor 9
wo wIII soo n boffor wny fo sforo sfrucfurod Informn-
fIon.
75 &rrays' S#i$es and (aps
Problems
l. How do you nccoss fho 4
fh
oIomonf of nn nrrny or
sIIco
2. Whnf Is fho Iongfh of n sIIco cronfod usIng:
ma&e5HIint< ?< A6
3. CIvon fho nrrny:
x :E H>Istrin.73a3<3b3<3c3<3d3<3e3<3438
whnf wouId xH:"I gIvo you
4. WrIfo n rogrnm fhnf fInds fho smnIIosf numbor
In fhIs IIsf:
x :E HIint7
@=<A><=><>=<
"P<=<>?<P/<
?P<?@<=?<P<
$A<AP< A<$P<
8
Functions
A funcfIon Is nn Indoondonf socfIon of codo fhnf mns
zoro or moro Inuf nrnmofors fo zoro or moro oufuf
nrnmofors. IuncfIons (nIso known ns rocoduros or
subroufInos) nro offon rorosonfod ns n bInck box: (fho
bInck box rorosonfs fho funcfIon)
!nfII now fho rogrnms wo hnvo wrIffon In Co hnvo
usod onIy ono funcfIon:
4unc main56 78
Wo wIII now bogIn wrIfIng rogrnms fhnf uso moro
fhnn ono funcfIon.
76
77 Fun$tions
.1 Your Second Function
!omombor fhIs rogrnm from chnfor 6:
4unc main56 7
xs :E HI4loat>@7A=<A?<PP<=<=?8
total :E /./
4or N< v :E ran.e xs 7
total BE v
8
4mt.+rintln5total / 4loat>@5len5xs666
8
ThIs rogrnm comufos fho nvorngo of n sorIos of num-
bors. IIndIng fho nvorngo IIko fhIs Is n vory gonornI
robIom, so Ifs nn IdonI cnndIdnfo for dofInIfIon ns n
funcfIon.
Tho avera.e funcfIon wIII nood fo fnko In n sIIco of
4loat>@s nnd rofurn ono 4loat>@. Insorf fhIs boforo fho
main funcfIon:
4unc avera.e5xs HI4loat>@6 4loat>@ 7
panic53Not :mplemented36
8
IuncfIons sfnrf wIfh fho koyword 4unc, foIIowod by fho
funcfIon's nnmo. Tho nrnmofors (Inufs) of fho func-
Fun$tions 78
fIon nro dofInod IIko fhIs: name t-pe< name t-pe< X.
Our funcfIon hns ono nrnmofor (fho IIsf of scoros) fhnf
wo nnmod xs. Affor fho nrnmofors wo uf fho rofurn
fyo. CoIIocfIvoIy fho nrnmofors nnd fho rofurn fyo
nro known ns fho funcfIon's sIgnnfuro.
IInnIIy wo hnvo fho funcfIon body whIch Is n sorIos of
sfnfomonfs bofwoon curIy brncos. In fhIs body wo In-
voko n buIIf-In funcfIon cnIIod panic whIch cnusos n
run fImo orror. (Wo'II soo moro nbouf nnIc Infor In
fhIs chnfor) WrIfIng funcfIons cnn bo dIffIcuIf so If's n
good Idon fo bronk fho rocoss Info mnnngonbIo
chunks, rnfhor fhnn fryIng fo ImIomonf fho onfIro
fhIng In ono Inrgo sfo.
ow Iofs fnko fho codo from our mnIn funcfIon nnd
movo If Info our nvorngo funcfIon:
4unc avera.e5xs HI4loat>@6 4loat>@ 7
total :E /./
4or N< v :E ran.e xs 7
total BE v
8
return total / 4loat>@5len5xs66
8
ofIco fhnf wo chnngod fho 4mt.+rintln fo bo n return
Insfond. Tho rofurn sfnfomonf cnusos fho funcfIon fo
ImmodInfoIy sfo nnd rofurn fho vnIuo nffor If fo fho
79 Fun$tions
funcfIon fhnf cnIIod fhIs ono. ModIfy main fo Iook IIko
fhIs:
4unc main56 7
xs :E HI4loat>@7A=<A?<PP<=<=?8
4mt.+rintln5avera.e5xs66
8
!unnIng fhIs rogrnm shouId gIvo you oxncfIy fho
snmo rosuIf ns fho orIgInnI. A fow fhIngs fo koo In
mInd:
Tho nnmos of fho nrnmofors don'f hnvo fo mnfch In
fho cnIIIng funcfIon. Ior oxnmIo wo couId hnvo dono
fhIs:
4unc main56 7
someTtherName :E HI4loat>@7A=<A?<PP<=<=?8
4mt.+rintln5avera.e5someTtherName66
8
And our rogrnm wouId sfIII work.
IuncfIons don'f hnvo nccoss fo nnyfhIng In fho cnII-
Ing funcfIon. ThIs won'f work:
Fun$tions 80
4unc 456 7
4mt.+rintln5x6
8
4unc main56 7
x :E "
456
8
Wo nood fo oIfhor do fhIs:
4unc 45x int6 7
4mt.+rintln5x6
8
4unc main56 7
x :E "
45x6
8
Or fhIs:
var x int E "
4unc 456 7
4mt.+rintln5x6
8
4unc main56 7
456
8
IuncfIons nro buIIf u In n sfnck. Suoso wo hnd
fhIs rogrnm:
81 Fun$tions
4unc main56 7
4mt.+rintln54$566
8
4unc 4$56 int 7
return 456
8
4unc 456 int 7
return $
8
Wo couId vIsunIIzo If IIko fhIs:
Inch fImo wo cnII n funcfIon wo ush If onfo fho cnII
sfnck nnd onch fImo wo rofurn from n funcfIon wo
o fho Insf funcfIon off of fho sfnck.
Wo cnn nIso nnmo fho rofurn fyo:
4unc 456 5r int6 7
r E $
return
8
Fun$tions 82
.2 5eturning $ultiple Values
Co Is nIso cnnbIo of rofurnIng muIfIIo vnIuos from n
funcfIon:
4unc 456 5int< int6 7
return "< >
8
4unc main56 7
x< - :E 456
8
Throo chnngos nro nocossnry: chnngo fho rofurn fyo
fo confnIn muIfIIo fyos sonrnfod by <, chnngo fho
oxrossIon nffor fho rofurn so fhnf If confnIns muIfIIo
oxrossIons sonrnfod by < nnd fInnIIy chnngo fho ns-
sIgnmonf sfnfomonf so fhnf muIfIIo vnIuos nro on fho
Ioff sIdo of fho :E or E.
MuIfIIo vnIuos nro offon usod fo rofurn nn orror vnIuo
nIong wIfh fho rosuIf (x< err :E 456), or n booIonn fo
IndIcnfo succoss (x< o& :E 456).
.3 Variadic Functions
Thoro Is n socInI form nvnIInbIo for fho Insf nrnmofor
In n Co funcfIon:
83 Fun$tions
4unc add5ar.s ...int6 int 7
total :E /
4or N< v :E ran.e ar.s 7
total BE v
8
return total
8
4unc main56 7
4mt.+rintln5add5$<<?66
8
Iy usIng ... boforo fho fyo nnmo of fho Insf nrnmo-
for you cnn IndIcnfo fhnf If fnkos zoro or moro of fhoso
nrnmofors. In fhIs cnso wo fnko zoro or moro ints. Wo
Invoko fho funcfIon IIko nny ofhor funcfIon oxcof wo
cnn nss ns mnny ints ns wo wnnf.
ThIs Is rocIsoIy how fho 4mt.+rintln funcfIon Is Im-
Iomonfod:
4unc +rintln5a ...inter4ace786 5n int< err
error6
Tho +rintln funcfIon fnkos nny numbor of vnIuos of
nny fyo. (Tho socInI inter4ace78 fyo wIII bo dIs-
cussod In moro dofnII In chnfor 9)
Wo cnn nIso nss n sIIco of ints by foIIowIng fho sIIco
wIfh ...:
Fun$tions 84
4unc main56 7
xs :E HIint7$<<?8
4mt.+rintln5add5xs...66
8
.4 Closure
If Is ossIbIo fo cronfo funcfIons InsIdo of funcfIons:
4unc main56 7
add :E 4unc5x< - int6 int 7
return x B -
8
4mt.+rintln5add5$<$66
8
add Is n IocnI vnrInbIo fhnf hns fho fyo 4unc5int< int6
int (n funcfIon fhnf fnkos fwo ints nnd rofurns nn
int). Whon you cronfo n IocnI funcfIon IIko fhIs If nIso
hns nccoss fo ofhor IocnI vnrInbIos (romombor scoo
from chnfor 4):
85 Fun$tions
4unc main56 7
x :E /
increment :E 4unc56 int 7
xBB
return x
8
4mt.+rintln5increment566
4mt.+rintln5increment566
8
increment ndds l fo fho vnrInbIo x whIch Is dofInod In
fho main funcfIon's scoo. ThIs x vnrInbIo cnn bo nc-
cossod nnd modIfIod by fho increment funcfIon. ThIs Is
why fho fIrsf fImo wo cnII increment wo soo l dIs-
Inyod, buf fho socond fImo wo cnII If wo soo 2 dIs-
Inyod.
A funcfIon IIko fhIs fogofhor wIfh fho non-IocnI vnrI-
nbIos If roforoncos Is known ns n cIosuro. In fhIs cnso
increment nnd fho vnrInbIo x form fho cIosuro.
Ono wny fo uso cIosuro Is by wrIfIng n funcfIon whIch
rofurns nnofhor funcfIon whIch whon cnIIod cnn
gonornfo n soquonco of numbors. Ior oxnmIo horo's
how wo mIghf gonornfo nII fho ovon numbors:
Fun$tions 86
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
ma&e;ven2enerator rofurns n funcfIon whIch gonornfos
ovon numbors. Inch fImo If's cnIIod If ndds 2 fo fho Io-
cnI i vnrInbIo whIch unIIko normnI IocnI vnrInbIos
orsIsfs bofwoon cnIIs.
.5 5ecursion
IInnIIy n funcfIon Is nbIo fo cnII IfsoIf. Horo Is ono wny
fo comufo fho fncforInI of n numbor:
87 Fun$tions
4unc 4actorial5x uint6 uint 7
i4 x EE / 7
return $
8
return x 9 4actorial5x#$6
8
4actorial cnIIs IfsoIf, whIch Is whnf mnkos fhIs func-
fIon rocursIvo. In ordor fo boffor undorsfnnd how fhIs
funcfIon works, Iofs wnIk fhrough 4actorial56:
Is x EE / o. (x Is 2)
IInd fho fncforInI of x Y $
Is x EE / o. (x Is l)
IInd fho 4actorial of x Y $
Is x EE / Yos, rofurn l.
rofurn $ 9 $
rofurn 9 $
CIosuro nnd rocursIon nro oworfuI rogrnmmIng foch-
nIquos whIch form fho bnsIs of n nrndIgm known ns
funcfIonnI rogrnmmIng. Mosf ooIo wIII fInd func-
fIonnI rogrnmmIng moro dIffIcuIf fo undorsfnnd fhnn
nn nronch bnsod on for Ioos, If sfnfomonfs, vnrI-
nbIos nnd sImIo funcfIons.
Fun$tions 88
.! 7e(er# Panic 8 5eco9er
Co hns n socInI sfnfomonf cnIIod de4er whIch schod-
uIos n funcfIon cnII fo bo run nffor fho funcfIon com-
Iofos. ConsIdor fho foIIowIng oxnmIo:
pac&a.e main
import 34mt3
4unc 4irst56 7
4mt.+rintln53$st36
8
4unc second56 7
4mt.+rintln53nd36
8
4unc main56 7
de4er second56
4irst56
8
ThIs rogrnm rInfs $st foIIowod by nd. InsIcnIIy do-
for movos fho cnII fo second fo fho ond of fho funcfIon:
4unc main56 7
4irst56
second56
8
de4er Is offon usod whon rosourcos nood fo bo frood In
somo wny. Ior oxnmIo whon wo oon n fIIo wo nood fo
89 Fun$tions
mnko suro fo cIoso If Infor. WIfh de4er:
4< N :E os.Tpen54ilename6
de4er 4.Close56
ThIs hns 3 ndvnnfngos: (l) If koos our Close cnII nonr
our Tpen cnII so Ifs onsIor fo undorsfnnd, (2) If our func-
fIon hnd muIfIIo rofurn sfnfomonfs (orhns ono In
nn i4 nnd ono In nn else) Close wIII hnon boforo
bofh of fhom nnd (3) doforrod funcfIons nro run ovon If
n run-fImo nnIc occurs.
Panic 8 5eco9er
InrIIor wo cronfod n funcfIon fhnf cnIIod fho panic
funcfIon fo cnuso n run fImo orror. Wo cnn hnndIo n
run-fImo nnIc wIfh fho buIIf-In recover funcfIon.
recover sfos fho nnIc nnd rofurns fho vnIuo fhnf wns
nssod fo fho cnII fo panic. Wo mIghf bo fomfod fo uso
If IIko fhIs:
Fun$tions 90
pac&a.e main
import 34mt3
4unc main56 7
panic53+WN:C36
str :E recover56
4mt.+rintln5str6
8
Iuf fho cnII fo recover wIII novor hnon In fhIs cnso
bocnuso fho cnII fo panic ImmodInfoIy sfos oxocufIon
of fho funcfIon. Insfond wo hnvo fo nIr If wIfh de4er:
pac&a.e main
import 34mt3
4unc main56 7
de4er 4unc56 7
str :E recover56
4mt.+rintln5str6
856
panic53+WN:C36
8
A nnIc gonornIIy IndIcnfos n rogrnmmor orror (for
oxnmIo nffomfIng fo nccoss nn Indox of nn nrrny
fhnf's ouf of bounds, forgoffIng fo InIfInIIzo n mn, ofc.)
or nn oxcofIonnI condIfIon fhnf fhoro's no onsy wny fo
rocovor from. (Honco fho nnmo nnIc)
91 Fun$tions
Problems
l. sum Is n funcfIon whIch fnkos n sIIco of numbors
nnd ndds fhom fogofhor. Whnf wouId Ifs func-
fIon sIgnnfuro Iook IIko In Co
2. WrIfo n funcfIon whIch fnkos nn Infogor nnd
hnIvos If nnd rofurns fruo If If wns ovon or fnIso
If If wns odd. Ior oxnmIo hal45$6 shouId rofurn
5/< 4alse6 nnd hal456 shouId rofurn 5$<
true6.
3. WrIfo n funcfIon wIfh ono vnrIndIc nrnmofor
fhnf fInds fho gronfosf numbor In n IIsf of num-
bors.
4. !sIng ma&e;ven2enerator ns nn oxnmIo, wrIfo n
ma&eTdd2enerator funcfIon fhnf gonornfos odd
numbors.
5. Tho IIbonnccI soquonco Is dofInod ns: 4ib5/6 E
/, 4ib5$6 E $, 4ib5n6 E 4ib5n#$6 B 4ib5n#6.
WrIfo n rocursIvo funcfIon whIch cnn fInd
4ib5n6.
6. Whnf nro dofor, nnIc nnd rocovor How do you
rocovor from n run-fImo nnIc
% Pointers
Whon wo cnII n funcfIon fhnf fnkos nn nrgumonf, fhnf
nrgumonf Is coIod fo fho funcfIon:
4unc Zero5x int6 7
x E /
8
4unc main56 7
x :E "
Zero5x6
4mt.+rintln5x6 // x is still "
8
In fhIs rogrnm fho Zero funcfIon wIII nof modIfy fho
orIgInnI x vnrInbIo In fho main funcfIon. Iuf whnf If wo
wnnfod fo Ono wny fo do fhIs Is fo uso n socInI dnfn
fyo known ns n oInfor:
92
93 Pointers
4unc Zero5x+tr 9int6 7
9x+tr E /
8
4unc main56 7
x :E "
Zero5Jx6
4mt.+rintln5x6 // x is /
8
IoInfors roforonco n IocnfIon In momory whoro n vnIuo
Is sforod rnfhor fhnn fho vnIuo IfsoIf. (Thoy oInf fo
somofhIng oIso) Iy usIng n oInfor (9int) fho Zero
funcfIon Is nbIo fo modIfy fho orIgInnI vnrInbIo.
%.1 T+e : and 8 operators
In Co n oInfor Is rorosonfod usIng fho 9 (nsforIsk)
chnrncfor foIIowod by fho fyo of fho sforod vnIuo. In
fho Zero funcfIon x+tr Is n oInfor fo nn int.
9 Is nIso usod fo doroforonco oInfor vnrInbIos. orof-
oroncIng n oInfor gIvos us nccoss fo fho vnIuo fho
oInfor oInfs fo. Whon wo wrIfo 9x+tr E / wo nro sny-
Ing sforo fho int 0 In fho momory IocnfIon x+tr rofors
fo. If wo fry x+tr E / Insfond wo wIII gof n comIIor
orror bocnuso x+tr Is nof nn int If's n 9int, whIch cnn
onIy bo gIvon nnofhor 9int.
IInnIIy wo uso fho J oornfor fo fInd fho nddross of n
Pointers 94
vnrInbIo. Jx rofurns n 9int (oInfor fo nn Inf) bocnuso x
Is nn int. ThIs Is whnf nIIows us fo modIfy fho orIgInnI
vnrInbIo. Jx In main nnd x+tr In Zero rofor fo fho snmo
momory IocnfIon.
%.2 ne0
Anofhor wny fo gof n oInfor Is fo uso fho buIIf-In ne)
funcfIon:
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
ne) fnkos n fyo ns nn nrgumonf, nIIocnfos onough
momory fo fIf n vnIuo of fhnf fyo nnd rofurns n
oInfor fo If.
In somo rogrnmmIng Inngungos fhoro Is n sIgnIfIcnnf
dIfforonco bofwoon usIng ne) nnd J, wIfh gronf cnro bo-
Ing noodod fo ovonfunIIy doIofo nnyfhIng cronfod wIfh
ne). Co Is nof IIko fhIs, If's n gnrbngo coIIocfod ro-
grnmmIng Inngungo whIch monns momory Is cIonnod
u nufomnfIcnIIy whon nofhIng rofors fo If nnymoro.
95 Pointers
IoInfors nro rnroIy usod wIfh Co's buIIf-In fyos, buf
ns wo wIII soo In fho noxf chnfor, fhoy nro oxfromoIy
usofuI whon nIrod wIfh sfrucfs.
Pointers 96
Problems
l. How do you gof fho momory nddross of n vnrI-
nbIo
2. How do you nssIgn n vnIuo fo n oInfor
3. How do you cronfo n now oInfor
4. Whnf Is fho vnIuo of x nffor runnIng fhIs ro-
grnm:
4unc s[uare5x 94loat>@6 7
9x E 9x 9 9x
8
4unc main56 7
x :E $."
s[uare5Jx6
8
5. WrIfo n rogrnm fhnf cnn swn fwo Infogors
(x :E $Q - :E Q s)ap5Jx< J-6 shouId gIvo you
xE nnd -E$).
& Structs and 'nter(aces
AIfhough If wouId bo ossIbIo for us fo wrIfo rogrnms
onIy usIng Co's buIIf-In dnfn fyos, nf somo oInf If
wouId bocomo quIfo fodIous. ConsIdor n rogrnm fhnf
Inforncfs wIfh shnos:
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
97
Stru$ts and )nter*a$es 98
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
8
KooIng frnck of nII fho coordInnfos mnkos If dIffIcuIf
fo soo whnf fho rogrnm Is doIng nnd wIII IIkoIy Iond fo
mIsfnkos.
&.1 Structs
An onsy wny fo mnko fhIs rogrnm boffor Is fo uso n
sfrucf. A sfrucf Is n fyo whIch confnIns nnmod fIoIds.
Ior oxnmIo wo couId rorosonf n CIrcIo IIko fhIs:
t-pe Circle struct 7
x 4loat>@
- 4loat>@
r 4loat>@
8
Tho t-pe koyword Infroducos n now fyo. If's foIIowod
by fho nnmo of fho fyo (Circle), fho koyword struct
fo IndIcnfo fhnf wo nro dofInIng n struct fyo nnd n
IIsf of fIoIds InsIdo of curIy brncos. Inch fIoId hns n
99 Stru$ts and )nter*a$es
nnmo nnd n fyo. !Iko wIfh funcfIons wo cnn coIInso
fIoIds fhnf hnvo fho snmo fyo:
t-pe Circle struct 7
x< -< r 4loat>@
8
'nitiali;ation
Wo cnn cronfo nn Insfnnco of our now CIrcIo fyo In n
vnrIofy of wnys:
var c Circle
!Iko wIfh ofhor dnfn fyos, fhIs wIII cronfo n IocnI CIr-
cIo vnrInbIo fhnf Is by dofnuIf sof fo zoro. Ior n struct
zoro monns onch of fho fIoIds Is sof fo fhoIr corrosond-
Ing zoro vnIuo (/ for ints, /./ for 4loats, 33 for strin.s,
nil for oInfors, .) Wo cnn nIso uso fho now funcfIon:
c :E ne)5Circle6
ThIs nIIocnfos momory for nII fho fIoIds, sofs onch of
fhom fo fhoIr zoro vnIuo nnd rofurns n oInfor.
(9Circle) Moro offon wo wnnf fo gIvo onch of fho fIoIds
n vnIuo. Wo cnn do fhIs In fwo wnys. !Iko fhIs:
Stru$ts and )nter*a$es 100
c :E Circle7x: /< -: /< r: "8
Or wo cnn Ionvo off fho fIoId nnmos If wo know fho or-
dor fhoy woro dofInod:
c :E Circle7/< /< "8
Fields
Wo cnn nccoss fIoIds usIng fho . oornfor:
4mt.+rintln5c.x< c.-< c.r6
c.x E $/
c.- E "
!of's modIfy fho circleWrea funcfIon so fhnf If usos n
Circle:
4unc circleWrea5c Circle6 4loat>@ 7
return math.+i 9 c.r9c.r
8
In mnIn wo hnvo:
c :E Circle7/< /< "8
4mt.+rintln5circleWrea5c66
101 Stru$ts and )nter*a$es
Ono fhIng fo romombor Is fhnf nrgumonfs nro nIwnys
coIod In Co. If wo nffomfod fo modIfy ono of fho
fIoIds InsIdo of fho circleWrea funcfIon, If wouId nof
modIfy fho orIgInnI vnrInbIo. Iocnuso of fhIs wo wouId
fyIcnIIy wrIfo fho funcfIon IIko fhIs:
4unc circleWrea5c 9Circle6 4loat>@ 7
return math.+i 9 c.r9c.r
8
And chnngo mnIn:
c :E Circle7/< /< "8
4mt.+rintln5circleWrea5Jc66
&.2 $et+ods
AIfhough fhIs Is boffor fhnn fho fIrsf vorsIon of fhIs
codo, wo cnn Imrovo If sIgnIfIcnnfIy by usIng n socInI
fyo of funcfIon known ns n mofhod:
4unc 5c 9Circle6 area56 4loat>@ 7
return math.+i 9 c.r9c.r
8
In bofwoon fho koyword 4unc nnd fho nnmo of fho
funcfIon wo'vo nddod n rocoIvor. Tho rocoIvor Is IIko n
Stru$ts and )nter*a$es 102
nrnmofor If hns n nnmo nnd n fyo buf by cronfIng
fho funcfIon In fhIs wny If nIIows us fo cnII fho funcfIon
usIng fho . oornfor:
4mt.+rintln5c.area566
ThIs Is much onsIor fo rond, wo no Iongor nood fho J
oornfor (Co nufomnfIcnIIy knows fo nss n oInfor fo
fho cIrcIo for fhIs mofhod) nnd bocnuso fhIs funcfIon
cnn onIy bo usod wIfh Circles wo cnn ronnmo fho func-
fIon fo jusf area.
!of's do fho snmo fhIng for fho rocfnngIo:
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 hns:
r :E \ectan.le7/< /< $/< $/8
4mt.+rintln5r.area566
103 Stru$ts and )nter*a$es
3mbedded Types
A sfrucf's fIoIds usunIIy rorosonf fho hns-n roInfIon-
shI. Ior oxnmIo n Circle hns n radius. Suoso wo
hnd n orson sfrucf:
t-pe +erson struct 7
Name strin.
8
4unc 5p 9+erson6 Ual&56 7
4mt.+rintln530i< m- name is3< p.Name6
8
And wo wnnfod fo cronfo n now Wndroid sfrucf. Wo
couId do fhIs:
t-pe Wndroid struct 7
+erson +erson
*odel strin.
8
ThIs wouId work, buf wo wouId rnfhor sny nn AndroId
is a Iorson, rnfhor fhnn nn AndroId as a Iorson. Co
suorfs roInfIonshIs IIko fhIs by usIng nn omboddod
fyo. AIso known ns nnonymous fIoIds, omboddod
fyos Iook IIko fhIs:
Stru$ts and )nter*a$es 104
t-pe Wndroid struct 7
+erson
*odel strin.
8
Wo uso fho fyo (+erson) nnd don'f gIvo If n nnmo.
Whon dofInod fhIs wny fho +erson sfrucf cnn bo nc-
cossod usIng fho fyo nnmo:
a :E ne)5Wndroid6
a.+erson.Ual&56
Iuf wo cnn nIso cnII nny +erson mofhods dIrocfIy on
fho Wndroid:
a :E ne)5Wndroid6
a.Ual&56
Tho Is-n roInfIonshI works fhIs wny InfuIfIvoIy: Ioo-
Io cnn fnIk, nn nndroId Is n orson, fhoroforo nn nn-
droId cnn fnIk.
&.3 'nter(aces
You mny hnvo nofIcod fhnf wo woro nbIo fo nnmo fho
\ectan.le's area mofhod fho snmo fhIng ns fho Circle's
area mofhod. ThIs wns no nccIdonf. In bofh ronI IIfo
105 Stru$ts and )nter*a$es
nnd In rogrnmmIng, roInfIonshIs IIko fhoso nro com-
monInco. Co hns n wny of mnkIng fhoso nccIdonfnI
sImIInrIfIos oxIIcIf fhrough n fyo known ns nn Infor-
fnco. Horo Is nn oxnmIo of n Shape Inforfnco:
t-pe Shape inter4ace 7
area56 4loat>@
8
!Iko n sfrucf nn Inforfnco Is cronfod usIng fho t-pe
koyword, foIIowod by n nnmo nnd fho koyword
inter4ace. Iuf Insfond of dofInIng fIoIds, wo dofIno n
mofhod sof. A mofhod sof Is n IIsf of mofhods fhnf n
fyo musf hnvo In ordor fo ImIomonf fho Inforfnco.
In our cnso bofh \ectan.le nnd Circle hnvo nron mofh-
ods whIch rofurn 4loat>@s so bofh fyos ImIomonf fho
Shape Inforfnco. Iy IfsoIf fhIs wouIdn'f bo nrfIcuInrIy
usofuI, buf wo cnn uso Inforfnco fyos ns nrgumonfs fo
funcfIons:
4unc totalWrea5shapes ...Shape6 4loat>@ 7
var area 4loat>@
4or N< s :E ran.e shapes 7
area BE s.area56
8
return area
8
Stru$ts and )nter*a$es 106
Wo wouId cnII fhIs funcfIon IIko fhIs:
4mt.+rintln5totalWrea5Jc< Jr66
Inforfncos cnn nIso bo usod ns fIoIds:
t-pe *ultiShape struct 7
shapes HIShape
8
Wo cnn ovon furn *ultiShape IfsoIf Info n Shape by gIv-
Ing If nn nron mofhod:
4unc 5m 9*ultiShape6 area56 4loat>@ 7
var area 4loat>@
4or N< s :E ran.e m.shapes 7
area BE s.area56
8
return area
8
ow n *ultiShape cnn confnIn Circles, \ectan.les or
ovon ofhor *ultiShapes.
107 Stru$ts and )nter*a$es
Problems
l. Whnf's fho dIfforonco bofwoon n mofhod nnd n
funcfIon
2. Why wouId you uso nn omboddod nnonymous
fIoId Insfond of n normnI nnmod fIoId
3. Add n now mofhod fo fho Shape Inforfnco cnIIod
perimeter whIch cnIcuInfos fho orImofor of n
shno. ImIomonf fho mofhod for Circle nnd
\ectan.le.
1) Concurrency
!nrgo rogrnms nro offon mndo u of mnny smnIIor
sub-rogrnms. Ior oxnmIo n wob sorvor hnndIos ro-
quosfs mndo from wob browsors nnd sorvos u HTM!
wob ngos In rosonso. Inch roquosf Is hnndIod IIko n
smnII rogrnm.
If wouId bo IdonI for rogrnms IIko fhoso fo bo nbIo fo
run fhoIr smnIIor comononfs nf fho snmo fImo (In fho
cnso of fho wob sorvor fo hnndIo muIfIIo roquosfs).
MnkIng rogross on moro fhnn ono fnsk sImuIfnno-
ousIy Is known ns concurroncy. Co hns rIch suorf for
concurroncy usIng goroufInos nnd chnnnoIs.
1).1 Goroutines
A goroufIno Is n funcfIon fhnf Is cnnbIo of runnIng
concurronfIy wIfh ofhor funcfIons. To cronfo n gorou-
fIno wo uso fho koyword .o foIIowod by n funcfIon Invo-
cnfIon:
108
109 %on$urren$y
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.Scanln5Jinput6
8
ThIs rogrnm consIsfs of fwo goroufInos. Tho fIrsf gor-
oufIno Is ImIIcIf nnd Is fho mnIn funcfIon IfsoIf. Tho
socond goroufIno Is cronfod whon wo cnII .o 45/6. or-
mnIIy whon wo Invoko n funcfIon our rogrnm wIII oxo-
cufo nII fho sfnfomonfs In n funcfIon nnd fhon rofurn
fo fho noxf IIno foIIowIng fho InvocnfIon. WIfh n gorou-
fIno wo rofurn ImmodInfoIy fo fho noxf IIno nnd don'f
wnIf for fho funcfIon fo comIofo. ThIs Is why fho cnII
fo fho Scanln funcfIon hns boon IncIudod; wIfhouf If
fho rogrnm wouId oxIf boforo boIng gIvon fho oorfu-
nIfy fo rInf nII fho numbors.
CoroufInos nro IIghfwoIghf nnd wo cnn onsIIy cronfo
fhousnnds of fhom. Wo cnn modIfy our rogrnm fo run
l0 goroufInos by doIng fhIs:
%on$urren$y 110
4unc main56 7
4or i :E /Q i R $/Q iBB 7
.o 45i6
8
var input strin.
4mt.Scanln5Jinput6
8
You mny hnvo nofIcod fhnf whon you run fhIs rogrnm
If sooms fo run fho goroufInos In ordor rnfhor fhnn sI-
muIfnnoousIy. !of's ndd somo doIny fo fho funcfIon us-
Ing time.Sleep nnd 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
111 %on$urren$y
4unc main56 7
4or i :E /Q i R $/Q iBB 7
.o 45i6
8
var input strin.
4mt.Scanln5Jinput6
8
4 rInfs ouf fho numbors from 0 fo l0, wnIfIng bofwoon
0 nnd 250 ms nffor onch ono. Tho goroufInos shouId
now run sImuIfnnoousIy.
1).2 C+annels
ChnnnoIs rovIdo n wny for fwo goroufInos fo commu-
nIcnfo wIfh ono nnofhor nnd synchronIzo fhoIr oxocu-
fIon. Horo Is nn oxnmIo rogrnm usIng chnnnoIs:
%on$urren$y 112
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
.o pin.er5c6
.o printer5c6
var input strin.
4mt.Scanln5Jinput6
8
ThIs rogrnm wIII rInf Ing forovor (hIf onfor fo
sfo If). A chnnnoI fyo Is rorosonfod wIfh fho koy-
word chan foIIowod by fho fyo of fho fhIngs fhnf nro
nssod on fho chnnnoI (In fhIs cnso wo nro nssIng
sfrIngs). Tho R# (Ioff nrrow) oornfor Is usod fo sond
113 %on$urren$y
nnd rocoIvo mossngos on fho chnnnoI. c R# 3pin.3
monns sond 3pin.3. ms. :E R# c monns rocoIvo n mos-
sngo nnd sforo If In ms.. Tho 4mt IIno couId nIso hnvo
boon wrIffon IIko fhIs: 4mt.+rintln5R#c6 In whIch cnso
wo couId romovo fho rovIous IIno.
!sIng n chnnnoI IIko fhIs synchronIzos fho fwo gorou-
fInos. Whon pin.er nffomfs fo sond n mossngo on fho
chnnnoI If wIII wnIf unfII printer Is rondy fo rocoIvo
fho mossngo. (fhIs Is known ns bIockIng) !of's ndd nn-
ofhor sondor fo fho rogrnm nnd soo whnf hnons.
Add fhIs funcfIon:
4unc pon.er5c chan strin.6 7
4or i :E /Q Q iBB 7
c R# 3pon.3
8
8
And modIfy main:
%on$urren$y 114
4unc main56 7
var c chan strin. E ma&e5chan strin.6
.o pin.er5c6
.o pon.er5c6
.o printer5c6
var input strin.
4mt.Scanln5Jinput6
8
Tho rogrnm wIII now fnko furns rInfIng Ing nnd
ong.
C+annel 7irection
Wo cnn socIfy n dIrocfIon on n chnnnoI fyo fhus ro-
sfrIcfIng If fo oIfhor sondIng or rocoIvIng. Ior oxnmIo
Ingor's funcfIon sIgnnfuro cnn bo chnngod fo fhIs:
4unc pin.er5c chanR# strin.6
ow c cnn onIy bo sonf fo. AffomfIng fo rocoIvo from c
wIII rosuIf In n comIIor orror. SImIInrIy wo cnn chnngo
rInfor fo fhIs:
4unc printer5c R#chan strin.6
115 %on$urren$y
A chnnnoI fhnf doosn'f hnvo fhoso rosfrIcfIons Is
known ns bI-dIrocfIonnI. A bI-dIrocfIonnI chnnnoI cnn
bo nssod fo n funcfIon fhnf fnkos sond-onIy or rocoIvo-
onIy chnnnoIs, buf fho rovorso Is nof fruo.
Select
Co hns n socInI sfnfomonf cnIIod select whIch works
IIko n s)itch buf for chnnnoIs:
%on$urren$y 116
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.Scanln5Jinput6
8
ThIs rogrnm rInfs from l ovory 2 soconds nnd
from 2 ovory 3 soconds. select Icks fho fIrsf chnnnoI
fhnf Is rondy nnd rocoIvos from If (or sonds fo If). If
117 %on$urren$y
moro fhnn ono of fho chnnnoIs nro rondy fhon If rnn-
domIy Icks whIch ono fo rocoIvo from. If nono of fho
chnnnoIs nro rondy, fho sfnfomonf bIocks unfII ono bo-
comos nvnIInbIo.
Tho select sfnfomonf Is offon usod fo ImIomonf n
fImoouf:
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
time.W4ter cronfos n chnnnoI nnd nffor fho gIvon durn-
fIon wIII sond fho curronf fImo on If. (wo woron'f Infor-
osfod In fho fImo so wo dIdn'f sforo If In n vnrInbIo) Wo
cnn nIso socIfy n de4ault cnso:
%on$urren$y 118
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
Tho dofnuIf cnso hnons ImmodInfoIy If nono of fho
chnnnoIs nro rondy.
6u((ered C+annels
If's nIso ossIbIo fo nss n socond nrnmofor fo fho
mnko funcfIon whon cronfIng n chnnnoI:
c :E ma&e5chan int< $6
ThIs cronfos n bufforod chnnnoI wIfh n cnncIfy of l.
ormnIIy chnnnoIs nro synchronous; bofh sIdos of fho
chnnnoI wIII wnIf unfII fho ofhor sIdo Is rondy. A
bufforod chnnnoI Is nsynchronous; sondIng or rocoIvIng
n mossngo wIII nof wnIf unIoss fho chnnnoI Is nIrondy
fuII.
119 %on$urren$y
Problems
l. How do you socIfy fho dIrocfIon of n chnnnoI
fyo
2. WrIfo your own Sleep funcfIon usIng time.W4ter.
3. Whnf Is n bufforod chnnnoI How wouId you cro-
nfo ono wIfh n cnncIfy of 20
11 Pac*ages
Co wns dosIgnod fo bo n Inngungo fhnf oncourngos
good soffwnro ongInoorIng rncfIcos. An Imorfnnf
nrf of hIgh qunIIfy soffwnro Is codo rouso ombodIod
In fho rIncIIo on'f !oonf YoursoIf.
As wo snw In chnfor ? funcfIons nro fho fIrsf Inyor wo
furn fo nIIow codo rouso. Co nIso rovIdos nnofhor
mochnnIsm for codo rouso: nckngos. onrIy ovory ro-
grnm wo'vo soon so fnr IncIudod fhIs IIno:
import 34mt3
4mt Is fho nnmo of n nckngo fhnf IncIudos n vnrIofy of
funcfIons roInfod fo formnffIng nnd oufuf fo fho
scroon. IundIIng codo In fhIs wny sorvos 3 urosos:
l. If roducos fho chnnco of hnvIng ovorInIng
nnmos. ThIs koos our funcfIon nnmos shorf nnd
succIncf
2. If orgnnIzos codo so fhnf Ifs onsIor fo fInd codo
120
121 Pa$+ages
you wnnf fo rouso.
3. If soods u fho comIIor by onIy roquIrIng ro-
comIInfIon of smnIIor chunks of n rogrnm. AI-
fhough wo uso fho nckngo 4mt, wo don'f hnvo fo
rocomIIo If ovory fImo wo chnngo our rogrnm.
11.1 Creating Pac*ages
Inckngos onIy ronIIy mnko sonso In fho confoxf of n
sonrnfo rogrnm whIch usos fhom. WIfhouf fhIs son-
rnfo rogrnm wo hnvo no wny of usIng fho nckngo wo
cronfo. !of's cronfo nn nIIcnfIon fhnf wIII uso n nck-
ngo wo wIII wrIfo. Cronfo n foIdor In '/2o/src/.olan.#
boo& cnIIod chapter$$. InsIdo fhnf foIdor cronfo n fIIo
cnIIod main..o whIch confnIns fhIs:
pac&a.e main
import 34mt3
import 3.olan.#boo&/chapter$$/math3
4unc main56 7
xs :E HI4loat>@7$<<?<@8
av. :E math.Wvera.e5xs6
4mt.+rintln5av.6
8
ow cronfo nnofhor foIdor InsIdo of fho chapter$$
Pa$+ages 122
foIdor cnIIod math. InsIdo of fhIs foIdor cronfo n fIIo
cnIIod math..o fhnf confnIns fhIs:
pac&a.e math
4unc Wvera.e5xs HI4loat>@6 4loat>@ 7
total :E 4loat>@5/6
4or N< x :E ran.e xs 7
total BE x
8
return total / 4loat>@5len5xs66
8
!sIng n formInnI In fho math foIdor you jusf cronfod
run .o install. ThIs wIII comIIo fho math..o rogrnm
nnd cronfo n IInknbIo objocf fIIo:
'/2o/p&./osNarch/.olan.#boo&/chapter$$/math.a.
(whoro os Is somofhIng IIko )indo)s nnd arch Is somo-
fhIng IIko amd>@)
ow go bnck fo fho chapter$$ foIdor nnd run .o run
main..o. You shouId soo .". Somo fhIngs fo nofo:
l. math Is fho nnmo of n nckngo fhnf Is nrf of
Co's sfnndnrd dIsfrIbufIon, buf sInco Co nck-
ngos cnn bo hIornrchIcnI wo nro snfo fo uso fho
snmo nnmo for our nckngo. (Tho ronI math nck-
ngo Is jusf math, ours Is .olan.#
boo&/chapter$$/math)
123 Pa$+ages
2. Whon wo Imorf our mnfh IIbrnry wo uso Ifs fuII
nnmo (import 3.olan.#boo&/chapter$$/math3),
buf InsIdo of fho math..o fIIo wo onIy uso fho Insf
nrf of fho nnmo (pac&a.e math).
3. Wo nIso onIy uso fho shorf nnmo math whon wo
roforonco funcfIons from our IIbrnry. If wo
wnnfod fo uso bofh IIbrnrIos In fho snmo ro-
grnm Co nIIows us fo uso nn nIIns:
import m 3.olan.#boo&/chapter$$/math3
4unc main56 7
xs :E HI4loat>@7$<<?<@8
av. :E m.Wvera.e5xs6
4mt.+rintln5av.6
8
m Is fho nIIns.
4. You mny hnvo nofIcod fhnf ovory funcfIon In fho
nckngos wo'vo soon sfnrf wIfh n cnIfnI Ioffor.
In Co If somofhIng sfnrfs wIfh n cnIfnI Ioffor
fhnf monns ofhor nckngos (nnd rogrnms) nro
nbIo fo soo If. If wo hnd nnmod fho funcfIon
avera.e Insfond of Wvera.e our main rogrnm
wouId nof hnvo boon nbIo fo soo If.
If's n good rncfIco fo onIy oxoso fho nrfs of
Pa$+ages 124
our nckngo fhnf wo wnnf ofhor nckngos usIng
nnd hIdo ovoryfhIng oIso. ThIs nIIows us fo
frooIy chnngo fhoso nrfs Infor wIfhouf hnvIng
fo worry nbouf bronkIng ofhor rogrnms, nnd If
mnkos our nckngo onsIor fo uso.
5. Inckngo nnmos mnfch fho foIdors fhoy fnII In.
Thoro nro wnys nround fhIs, buf If's n Iof onsIor
If you sfny wIfhIn fhIs nfforn.
11.2 7ocumentation
Co hns fho nbIIIfy fo nufomnfIcnIIy gonornfo documon-
fnfIon for nckngos wo wrIfo In n sImIInr wny fo fho
sfnndnrd nckngo documonfnfIon. In n formInnI run
fhIs commnnd:
.odoc .olan.#boo&/chapter$$/math Wvera.e
You shouId soo InformnfIon dIsInyod for fho funcfIon
wo jusf wrofo. Wo cnn Imrovo fhIs documonfnfIon by
nddIng n commonf boforo fho funcfIon:
// !inds the avera.e o4 a series o4 numbers
4unc Wvera.e5xs HI4loat>@6 4loat>@ 7
If you run .o install In fho math foIdor, fhon ro-run
125 Pa$+ages
fho .odoc commnnd you shouId soo our commonf boIow
fho funcfIon dofInIfIon. ThIs documonfnfIon Is nIso
nvnIInbIo In wob form by runnIng fhIs commnnd:
.odoc #httpE3:>/>/3
nnd onforIng fhIs !!! Info your browsor:
http://localhost:>/>//p&./
You shouId bo nbIo fo browso fhrough nII of fho nck-
ngos InsfnIIod on your sysfom.
Pa$+ages 126
Problems
l. Why do wo uso nckngos
2. Whnf Is fho dIfforonco bofwoon nn IdonfIfIor
fhnf sfnrfs wIfh n cnIfnI Ioffor nnd ono whIch
doosn`f (Wvera.e vs avera.e)
3. Whnf Is n nckngo nIIns How do you mnko ono
4. Wo coIod fho nvorngo funcfIon from chnfor ?
fo our now nckngo. Cronfo *in nnd *ax func-
fIons whIch fInd fho mInImum nnd mnxImum
vnIuos In n sIIco of 4loat>@s.
5. How wouId you documonf fho funcfIons you cro-
nfod In #3
12 Testing
IrogrnmmIng Is nof onsy; ovon fho bosf rogrnmmors
nro IncnnbIo of wrIfIng rogrnms fhnf work oxncfIy ns
Infondod ovory fImo. Thoroforo nn Imorfnnf nrf of
fho soffwnro dovoIomonf rocoss Is fosfIng. WrIfIng
fosfs for our codo Is n good wny fo onsuro qunIIfy nnd
Imrovo roIInbIIIfy.
Co IncIudos n socInI rogrnm fhnf mnkos wrIfIng
fosfs onsIor, so Iof's cronfo somo fosfs for fho nckngo
wo mndo In fho Insf chnfor. In fho math foIdor from
chapter$$ cronfo n now fIIo cnIIod mathNtest..o fhnf
confnIns fhIs:
127
Testing 128
pac&a.e math
import 3testin.3
4unc UestWvera.e5t 9testin..U6 7
var v 4loat>@
v E Wvera.e5HI4loat>@7$<86
i4 v LE $." 7
t.;rror53;xpected $."< .ot 3< v6
8
8
ow run fhIs commnnd:
.o test
You shouId soo fhIs:
( .o test
+WSS
o& .olan.#boo&/chapter$$/math /./?s
Tho .o test commnnd wIII Iook for nny fosfs In nny of
fho fIIos In fho curronf foIdor nnd run fhom. Tosfs nro
IdonfIfIod by sfnrfIng n funcfIon wIfh fho word Uest
nnd fnkIng ono nrgumonf of fyo 9testin..U. In our
cnso sInco wo'ro fosfIng fho Wvera.e funcfIon wo nnmo
fho fosf funcfIon UestWvera.e.
129 Testing
Onco wo hnvo fho fosfIng funcfIon sofu wo wrIfo fosfs
fhnf uso fho codo wo'ro fosfIng. In fhIs cnso wo know
fho nvorngo of H$<I shouId bo $." so fhnf's whnf wo
chock. If's robnbIy n good Idon fo fosf mnny dIfforonf
combInnfIons of numbors so Iof's chnngo our fosf ro-
grnm n IIffIo:
pac&a.e math
import 3testin.3
t-pe testpair struct 7
values HI4loat>@
avera.e 4loat>@
8
var tests E HItestpair7
7 HI4loat>@7$<8< $." 8<
7 HI4loat>@7$<$<$<$<$<$8< $ 8<
7 HI4loat>@7#$<$8< / 8<
8
4unc UestWvera.e5t 9testin..U6 7
4or N< pair :E ran.e tests 7
v :E Wvera.e5pair.values6
i4 v LE pair.avera.e 7
t.;rror5
3!or3< pair.values<
3expected3< pair.avera.e<
3.ot3< v<
6
8
8
8
Testing 130
ThIs Is n vory common wny fo sofu fosfs (nbundnnf
oxnmIos cnn bo found In fho sourco codo for fho nck-
ngos IncIudod wIfh Co). Wo cronfo n struct fo roro-
sonf fho Inufs nnd oufufs for fho funcfIon. Thon wo
cronfo n IIsf of fhoso structs (nIrs). Thon wo Ioo
fhrough onch ono nnd run fho funcfIon.
131 Testing
Problems
l. WrIfIng n good suIfo of fosfs Is nof nIwnys onsy,
buf fho rocoss of wrIfIngs fosfs offon rovonIs
moro nbouf n robIom fhon you mny nf fIrsf ro-
nIIzo. Ior oxnmIo, wIfh our Wvera.e funcfIon
whnf hnons If you nss In nn omfy IIsf
(HI4loat>@78) How couId wo modIfy fho func-
fIon fo rofurn / In fhIs cnso
2. WrIfo n sorIos of fosfs for fho *in nnd *ax func-
fIons you wrofo In fho rovIous chnfor.
13 T+e Core Pac*ages
Insfond of wrIfIng ovoryfhIng from scrnfch, mosf ronI
worId rogrnmmIng doonds on our nbIIIfy fo Inforfnco
wIfh oxIsfIng IIbrnrIos. ThIs chnfor wIII fnko n Iook nf
somo of fho mosf commonIy usod nckngos IncIudod
wIfh Co.
IIrsf n word of wnrnIng: nIfhough somo of fhoso II-
brnrIos nro fnIrIy obvIous (or hnvo boon oxInInod In
rovIous chnfors), mnny of fho IIbrnrIos IncIudod wIfh
Co roquIro socInIIzod domnIn socIfIc knowIodgo (for
oxnmIo: cryfogrnhy). If Is boyond fho scoo of fhIs
book fo oxInIn fhoso undorIyIng fochnoIogIos.
13.1 Strings
Co IncIudos n Inrgo numbor of funcfIons fo work wIfh
sfrIngs In fho strin.s nckngo:
132
133 Te %ore Pa$+ages
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.]oin5HIstrin.73a3<3b38< 3#36<
// EE 3aaaaa3
strin.s.\epeat53a3< "6<
// 3bbaa3
strin.s.\eplace53aaaa3< 3a3< 3b3< 6<
// HIstrin.73a3<3b3<3c3<3d3<3e38
strin.s.Split53a#b#c#d#e3< 3#36<
Te %ore Pa$+ages 134
// 3test3
strin.s.Uo,o)er53U;SU36<
// 3U;SU3
strin.s.UoUpper53test36<
6
8
SomofImos wo nood fo work wIfh sfrIngs ns bInnry
dnfn. To convorf n sfrIng fo n sIIco of byfos (nnd vIco-
vorsn) do fhIs:
arr :E HIb-te53test36
str :E strin.5HIb-te7OtO<OeO<OsO<OtO86
13.2 'nput < 1utput
Ioforo wo Iook nf fIIos wo nood fo undorsfnnd Co's io
nckngo. Tho io nckngo consIsfs of n fow funcfIons,
buf mosfIy Inforfncos usod In ofhor nckngos. Tho fwo
mnIn Inforfncos nro \eader nnd 1riter. \eaders suorf
rondIng vIn fho \ead mofhod. 1riters suorf wrIfIng
vIn fho 1rite mofhod. Mnny funcfIons In Co fnko
\eaders or 1riters ns nrgumonfs. Ior oxnmIo fho io
nckngo hns n Cop- funcfIon whIch coIos dnfn from n
\eader fo n 1riter:
135 Te %ore Pa$+ages
4unc Cop-5dst 1riter< src \eader6 5)ritten
int>@< err error6
To rond or wrIfo fo n HIb-te or n strin. you cnn uso
fho Bu44er sfrucf found In fho b-tes nckngo:
var bu4 b-tes.Bu44er
bu4.1rite5HIb-te53test366
A Bu44er doosn'f hnvo fo bo InIfInIIzod nnd suorfs
bofh fho \eader nnd 1riter Inforfncos. You cnn convorf
If Info n HIb-te by cnIIIng bu4.B-tes56. If you onIy nood
fo rond from n sfrIng you cnn nIso uso fho
strin.s.Ne)\eader funcfIon whIch Is moro offIcIonf
fhnn usIng n buffor.
13.3 Files 8 Folders
To oon n fIIo In Co uso fho Tpen funcfIon from fho os
nckngo. Horo Is nn oxnmIo of how fo rond fho con-
fonfs of n fIIo nnd dIsIny fhom on fho formInnI:
Te %ore Pa$+ages 136
pac&a.e main
import 5
34mt3
3os3
6
4unc main56 7
4ile< err :E os.Tpen53test.txt36
i4 err LE nil 7
// handle the error here
return
8
de4er 4ile.Close56
// .et the 4ile siZe
stat< err :E 4ile.Stat56
i4 err LE nil 7
return
8
// read the 4ile
bs :E ma&e5HIb-te< stat.SiZe566
N< err E 4ile.\ead5bs6
i4 err LE nil 7
return
8
str :E strin.5bs6
4mt.+rintln5str6
8
Wo uso de4er 4ile.Close56 rIghf nffor oonIng fho fIIo
fo mnko suro fho fIIo Is cIosod ns soon ns fho funcfIon
137 Te %ore Pa$+ages
comIofos. !ondIng fIIos Is vory common, so fhoro's n
shorfor wny fo do fhIs:
pac&a.e main
import 5
34mt3
3io/ioutil3
6
4unc main56 7
bs< err :E ioutil.\ead!ile53test.txt36
i4 err LE nil 7
return
8
str :E strin.5bs6
4mt.+rintln5str6
8
Horo Is how wo cnn cronfo n fIIo:
Te %ore Pa$+ages 138
pac&a.e main
import 5
3os3
6
4unc main56 7
4ile< err :E os.Create53test.txt36
i4 err LE nil 7
// handle the error here
return
8
de4er 4ile.Close56
4ile.1riteStrin.53test36
8
To gof fho confonfs of n dIrocfory wo uso fho snmo
os.Tpen funcfIon buf gIvo If n dIrocfory nfh Insfond of
n fIIo nnmo. Thon wo cnII fho \eaddir mofhod:
139 Te %ore Pa$+ages
pac&a.e main
import 5
34mt3
3os3
6
4unc main56 7
dir< err :E os.Tpen53.36
i4 err LE nil 7
return
8
de4er dir.Close56
4ile:n4os< err :E dir.\eaddir5#$6
i4 err LE nil 7
return
8
4or N< 4i :E ran.e 4ile:n4os 7
4mt.+rintln54i.Name566
8
8
Offon wo wnnf fo rocursIvoIy wnIk n foIdor (rond fho
foIdor's confonfs, nII fho sub-foIdors, nII fho sub-sub-
foIdors, .). To mnko fhIs onsIor fhoro's n 1al& funcfIon
rovIdod In fho path/4ilepath nckngo:
Te %ore Pa$+ages 140
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
Tho funcfIon you nss fo 1al& Is cnIIod for ovory fIIo
nnd foIdor In fho roof foIdor. (In fhIs cnso .)
13.4 3rrors
Co hns n buIIf-In fyo for orrors fhnf wo hnvo nIrondy
soon (fho error fyo). Wo cnn cronfo our own orrors by
usIng fho Ne) funcfIon In fho errors nckngo:
141 Te %ore Pa$+ages
pac&a.e main
import 3errors3
4unc main56 7
err :E errors.Ne)53error messa.e36
8
13.5 Containers 8 Sort
In nddIfIon fo IIsfs nnd mns Co hns sovornI moro coI-
IocfIons nvnIInbIo undornonfh fho confnInor nckngo.
Wo'II fnko n Iook nf fho container/list nckngo ns nn
oxnmIo.
=ist
Tho container/list nckngo ImIomonfs n dou-
bIy-IInkod IIsf. A IInkod IIsf Is n fyo of dnfn sfrucfuro
fhnf Iooks IIko fhIs:
Inch nodo of fho IIsf confnIns n vnIuo (l, 2, or 3 In fhIs
cnso) nnd n oInfor fo fho noxf nodo. SInco fhIs Is n
doubIy-IInkod IIsf onch nodo wIII nIso hnvo oInfors fo
fho rovIous nodo. ThIs IIsf couId bo cronfod by fhIs
Te %ore Pa$+ages 142
rogrnm:
pac&a.e main
import 534mt3 Q 3container/list36
4unc main56 7
var x list.,ist
x.+ushBac&5$6
x.+ushBac&56
x.+ushBac&5?6
4or e :E x.!ront56Q e LE nilQ eEe.Next56 7
4mt.+rintln5e.Value.5int66
8
8
Tho zoro vnIuo for n ,ist Is nn omfy IIsf (n 9,ist cnn
nIso bo cronfod usIng list.Ne)). VnIuos nro nondod
fo fho IIsf usIng +ushBac&. Wo Ioo ovor onch Ifom In
fho IIsf by goffIng fho fIrsf oIomonf, nnd foIIowIng nII
fho IInks unfII wo ronch nII.
Sort
Tho sorf nckngo confnIns funcfIons for sorfIng nrbI-
frnry dnfn. Thoro nro sovornI rodofInod sorfIng func-
fIons (for sIIcos of Infs nnd fIonfs) Horo's nn oxnmIo
for how fo sorf your own dnfn:
143 Te %ore Pa$+ages
pac&a.e main
import 534mt3 Q 3sort36
t-pe +erson struct 7
Name strin.
W.e int
8
t-pe B-Name HI+erson
4unc 5this B-Name6 ,en56 int 7
return len5this6
8
4unc 5this B-Name6 ,ess5i< j int6 bool 7
return thisHiI.Name R thisHjI.Name
8
4unc 5this B-Name6 S)ap5i< j int6 7
thisHiI< thisHjI E thisHjI< thisHiI
8
4unc main56 7
&ids :E HI+erson7
73]ill3<A8<
73]ac&3<$/8<
8
sort.Sort5B-Name5&ids66
4mt.+rintln5&ids6
8
Tho Sort funcfIon In sort fnkos n sort.:nter4ace nnd
sorfs If. Tho sort.:nter4ace roquIros 3 mofhods: ,en,
,ess nnd S)ap. To dofIno our own sorf wo cronfo n now
fyo (B-Name) nnd mnko If oquIvnIonf fo n sIIco of whnf
Te %ore Pa$+ages 144
wo wnnf fo sorf. Wo fhon dofIno fho 3 mofhods.
SorfIng our IIsf of ooIo Is fhon ns onsy ns cnsfIng fho
IIsf Info our now fyo. Wo couId nIso sorf by ngo by do-
Ing fhIs:
t-pe B-W.e HI+erson
4unc 5this B-W.e6 ,en56 int 7
return len5this6
8
4unc 5this B-W.e6 ,ess5i< j int6 bool 7
return thisHiI.W.e R thisHjI.W.e
8
4unc 5this B-W.e6 S)ap5i< j int6 7
thisHiI< thisHjI E thisHjI< thisHiI
8
13.! 4as+es 8 Cryptograp+y
A hnsh funcfIon fnkos n sof of dnfn nnd roducos If fo n
smnIIor fIxod sIzo. Hnshos nro froquonfIy usod In ro-
grnmmIng for ovoryfhIng from IookIng u dnfn fo ons-
IIy dofocfIng chnngos. Hnsh funcfIons In Co nro brokon
Info fwo cnfogorIos: cryfogrnhIc nnd non-cryfo-
grnhIc.
Tho non-cryfogrnhIc hnsh funcfIons cnn bo found
undornonfh fho hnsh nckngo nnd IncIudo adler?,
crc?, crc>@ nnd 4nv. Horo's nn oxnmIo usIng crc?:
145 Te %ore Pa$+ages
pac&a.e main
import 5
34mt3
3hash/crc?3
6
4unc main56 7
h :E crc?.Ne):;;;56
h.1rite5HIb-te53test366
v :E h.Sum?56
4mt.+rintln5v6
8
Tho crc? hnsh objocf ImIomonfs fho 1riter Infor-
fnco, so wo cnn wrIfo byfos fo If IIko nny ofhor 1riter.
Onco wo'vo wrIffon ovoryfhIng wo wnnf wo cnII
Sum?56 fo rofurn n uint?. A common uso for crc? Is
fo comnro fwo fIIos. If fho Sum? vnIuo for bofh fIIos Is
fho snmo, If's hIghIy IIkoIy (fhough nof l00 corfnIn)
fhnf fho fIIos nro fho snmo. If fho vnIuos nro dIfforonf
fhon fho fIIos nro dofInIfoIy nof fho snmo:
Te %ore Pa$+ages 146
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!ile53test$.txt36
i4 err LE 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 LE nil 7
return
8
h< err :E .et0ash53test.txt36
i4 err LE nil 7
return
8
4mt.+rintln5h$< h< h$ EE h6
8
CryfogrnhIc hnsh funcfIons nro sImIInr fo fhoIr non-
cryfogrnhIc counfornrfs, buf fhoy hnvo fho nddod
roorfy of boIng hnrd fo rovorso. CIvon fho cryfo-
grnhIc hnsh of n sof of dnfn, If's oxfromoIy dIffIcuIf fo
147 Te %ore Pa$+ages
doformIno whnf mndo fho hnsh. Thoso hnshos nro of-
fon usod In socurIfy nIIcnfIons.
Ono common cryfogrnhIc hnsh funcfIon Is known ns
SHA-l. Horo's how If Is usod:
pac&a.e main
import 5
34mt3
3cr-pto/sha$3
6
4unc main56 7
h :E sha$.Ne)56
h.1rite5HIb-te53test366
bs :E h.Sum5HIb-te786
4mt.+rintln5bs6
8
ThIs oxnmIo Is vory sImIInr fo fho crc? ono, bocnuso
bofh crc? nnd sha$ ImIomonf fho hash.0ash Infor-
fnco. Tho mnIn dIfforonco Is fhnf whorons crc? com-
ufos n 32 bIf hnsh, sha$ comufos n l60 bIf hnsh.
Thoro Is no nnfIvo fyo fo rorosonf n l60 bIf numbor,
so wo uso n sIIco of 20 byfos Insfond.
13. Ser9ers
WrIfIng nofwork sorvors In Co Is vory onsy. Wo wIII
Te %ore Pa$+ages 148
fIrsf fnko n Iook nf how fo cronfo n TCI sorvor:
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 LE nil 7
4mt.+rintln5err6
return
8
4or 7
// accept a connection
c< err :E ln.Wccept56
i4 err LE nil 7
4mt.+rintln5err6
continue
8
// handle the connection
.o handleServerConnection5c6
8
8
149 Te %ore Pa$+ages
4unc handleServerConnection5c net.Conn6 7
// receive the messa.e
var ms. strin.
err :E .ob.Ne)%ecoder5c6.%ecode5Jms.6
i4 err LE nil 7
4mt.+rintln5err6
8 else 7
4mt.+rintln53\eceived3< ms.6
8
c.Close56
8
4unc client56 7
// connect to the server
c< err :E net.%ial53tcp3< 3$P././.$:AAAA36
i4 err LE 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 LE nil 7
4mt.+rintln5err6
8
c.Close56
8
Te %ore Pa$+ages 150
4unc main56 7
.o server56
.o client56
var input strin.
4mt.Scanln5Jinput6
8
ThIs oxnmIo usos fho encodin./.ob nckngo whIch
mnkos If onsy fo oncodo Co vnIuos so fhnf ofhor Co
rogrnms (or fho snmo Co rogrnm In fhIs cnso) cnn
rond fhom. AddIfIonnI oncodIngs nro nvnIInbIo In nck-
ngos undornonfh encodin. (IIko encodin./json) ns woII
ns In 3
rd
nrfy nckngos. (for oxnmIo wo couId uso
labix.or./v/m.o/bson for bson suorf)
4TTP
HTTI sorvors nro ovon onsIor fo sofu nnd uso:
151 Te %ore Pa$+ages
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<
GRdoct-pe html>
Rhtml>
Rhead>
Rtitle>0ello 1orldR/title>
R/head>
Rbod->
0ello 1orldL
R/bod->
R/html>G<
6
8
4unc main56 7
http.0andle!unc53/hello3< hello6
http.,istenWndServe53:A///3< nil6
8
0andle!unc hnndIos n !!! roufo (/hello) by cnIIIng fho
gIvon funcfIon. Wo cnn nIso hnndIo sfnfIc fIIos by usIng
!ileServer:
Te %ore Pa$+ages 152
http.0andle5
3/assets/3<
http.Strip+re4ix5
3/assets/3<
http.!ileServer5http.%ir53assets366<
6<
6
5PC
Tho net/rpc (romofo rocoduro cnII) nnd
net/rpc/jsonrpc nckngos rovIdo nn onsy wny fo ox-
oso mofhods so fhoy cnn bo Invokod ovor n nofwork.
(rnfhor fhnn jusf In fho rogrnm runnIng fhom)
153 Te %ore Pa$+ages
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 LE nil 7
4mt.+rintln5err6
return
8
4or 7
c< err :E ln.Wccept56
i4 err LE nil 7
continue
8
.o rpc.ServeConn5c6
8
8
Te %ore Pa$+ages 154
4unc client56 7
c< err :E rpc.%ial53tcp3< 3$P././.$:AAAA36
i4 err LE nil 7
4mt.+rintln5err6
return
8
var result int>@
err E c.Call53Server.Ne.ate3< int>@5AAA6<
Jresult6
i4 err LE nil 7
4mt.+rintln5err6
8 else 7
4mt.+rintln53Server.Ne.ate5AAA6 E3<
result6
8
8
4unc main56 7
.o server56
.o client56
var input strin.
4mt.Scanln5Jinput6
8
ThIs rogrnm Is sImIInr fo fho TCI oxnmIo, oxcof
now wo cronfod nn objocf fo hoId nII fho mofhods wo
wnnf fo oxoso nnd wo cnII fho Ne.ate mofhod from fho
cIIonf. Soo fho documonfnfIon In net/rpc for moro do-
fnIIs.
155 Te %ore Pa$+ages
13.% Parsing Command =ine "rguments
Whon wo Invoko n commnnd on fho formInnI If's ossI-
bIo fo nss fhnf commnnd nrgumonfs. Wo'vo soon fhIs
wIfh fho .o commnnd:
.o run m-4ile..o
run nnd myfIIo.go nro nrgumonfs. Wo cnn nIso nss
fIngs fo n commnnd:
.o run #v m-4ile..o
Tho fIng nckngo nIIows us fo nrso nrgumonfs nnd
fIngs sonf fo our rogrnm. Horo's nn oxnmIo rogrnm
fhnf gonornfos n numbor bofwoon 0 nnd 6. Wo cnn
chnngo fho mnx vnIuo by sondIng n fIng (#maxE$//) fo
fho rogrnm:
Te %ore Pa$+ages 156
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
Any nddIfIonnI non-fIng nrgumonfs cnn bo rofrIovod
wIfh 4la..Wr.s56 whIch rofurns n HIstrin..
13.& Sync+roni;ation Primiti9es
Tho roforrod wny fo hnndIo concurroncy nnd synchro-
nIznfIon In Co Is fhrough goroufInos nnd chnnnoIs ns
dIscussod In chnfor l0. Howovor Co doos rovIdo
moro frndIfIonnI muIfIfhrondIng roufInos In fho s-nc
nnd s-nc/atomic nckngos.
$ute-es
A mufox (mufnI oxcIusIvo Iock) Iocks n socfIon of codo
fo n sIngIo fhrond nf n fImo nnd Is usod fo rofocf
shnrod rosourcos from non-nfomIc oornfIons. Horo Is
nn oxnmIo of n mufox:
157 Te %ore Pa$+ages
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.Scanln5Jinput6
8
Whon fho mufox (m) Is Iockod nny ofhor nffomf fo Iock
If wIII bIock unfII If Is unIockod. Cronf cnro shouId bo
fnkon whon usIng mufoxos or fho synchronIznfIon
rImIfIvos rovIdod In fho s-nc/atomic nckngo.
TrndIfIonnI muIfIfhrondod rogrnmmIng Is dIffIcuIf;
If's onsy fo mnko mIsfnkos nnd fhoso mIsfnkos nro
hnrd fo fInd, sInco fhoy mny doond on n vory socIfIc,
roInfIvoIy rnro, nnd dIffIcuIf fo roroduco sof of cIrcum-
Te %ore Pa$+ages 158
sfnncos. Ono of Co's bIggosf sfrongfhs Is fhnf fho con-
curroncy fonfuros If rovIdos nro much onsIor fo undor-
sfnnd nnd uso roorIy fhnn fhronds nnd Iocks.
14 ,e-t Steps
Wo now hnvo nII fho InformnfIon wo nood fo wrIfo
mosf Co rogrnms. Iuf If wouId bo dnngorous fo con-
cIudo fhnf fhoroforo wo nro comofonf rogrnmmors.
IrogrnmmIng Is ns much n crnff ns If Is jusf hnvIng
knowIodgo. ThIs chnfor wIII rovIdo you wIfh somo
suggosfIons nbouf how bosf fo mnsfor fho crnff of ro-
grnmmIng.
14.1 Study t+e $asters
Inrf of bocomIng n good nrfIsf or wrIfor Is sfudyIng fho
works of fho mnsfors. If's no dIfforonf wIfh rogrnm-
mIng. Ono of fho bosf wnys fo bocomo n skIIIod ro-
grnmmor Is fo sfudy fho sourco codo roducod by ofh-
ors. Co Is woII suIfod fo fhIs fnsk sInco fho sourco codo
for fho onfIro rojocf Is frooIy nvnIInbIo.
Ior oxnmIo wo mIghf fnko n Iook nf fho sourco codo fo
fho io/ioutil IIbrnry nvnIInbIo nf:
hff://goInng.org/src/kg/Io/IoufII/IoufII.go
159
,e-t Steps 160
!ond fho codo sIowIy nnd doIIbornfoIy. Try fo undor-
sfnnd ovory IIno nnd rond fho suIIod commonfs. Ior
oxnmIo In fho \ead!ile mofhod fhoro's n commonf
fhnf snys fhIs:
// :tOs a .ood but not certain bet that !ile:n4o
// )ill tell us exactl- ho) much to read< so
// letOs tr- it but be prepared 4or the ans)er
// to be )ron..
ThIs mofhod robnbIy sfnrfod ouf sImIor fhnn whnf If
bocnmo so fhIs Is n gronf oxnmIo of how rogrnms cnn
ovoIvo nffor fosfIng nnd why If's Imorfnnf fo suIy
commonfs wIfh fhoso chnngos. AII of fho sourco codo
for nII of fho nckngos Is nvnIInbIo nf:
hff://goInng.org/src/kg/
14.2 $a*e Somet+ing
Ono of fho bosf wnys fo hono your skIIIs Is fo rncfIco
codIng. Thoro nro n Iof of wnys fo do fhIs: You couId
work on chnIIongIng rogrnmmIng robIoms from sIfos
IIko Irojocf IuIor (hff://rojocfouIor.nof/) or fry your
hnnd nf n Inrgor rojocf. Iorhns fry fo ImIomonf n
wob sorvor or wrIfo n sImIo gnmo.
161 ,e-t Steps
14.3 Team >p
Mosf ronI-worId soffwnro rojocfs nro dono In fonms,
fhoroforo IonrnIng how fo work In n fonm Is crucInI. If
you cnn, fInd n frIond mnybo n cInssmnfo nnd fonm
u on n rojocf. !onrn how fo dIvIdo n rojocf Info
Iocos you cnn bofh work on sImuIfnnoousIy.
Anofhor ofIon Is fo work on nn oon sourco rojocf.
IInd n 3
rd
nrfy IIbrnry, wrIfo somo codo (orhns fIx n
bug), nnd submIf If fo fho mnInfnInor. Co hns n grow-
Ing communIfy whIch cnn bo ronchod vIn fho mnIIIng
IIsf (hff://grous.googIo.com/grou/goInng-nufs).

Você também pode gostar