go Language book
-
Upload
dharshan-raj -
Category
Documents
-
view
233 -
download
0
Transcript of go Language book
-
8/22/2019 go Language book
1/165
-
8/22/2019 go Language book
2/165
An Introduction to Programming in Go
Copyright 2012 by Caleb Doxsey
All rights reserved !o part o" this boo# may be
reproduced or transmitted in any "orm or by any
means$ electronic or mechanical$ including
photocopying$ recording$ or by any in"ormation storage
and retrieval system %ithout the %ritten permission o"
the author$ except %here permitted by la%
I&'!( )*+,1-*+.//+2.
Cover art by Abigail Doxsey Anderson
Portions o" this text are reproduced "rom %or# created
and shared by Google and used according to terms
described in the Creative Commons .0 Attribution
icense
-
8/22/2019 go Language book
3/165
Contents
1 Getting Started 1
11 iles and olders 2
12 he erminal /
1. ext 3ditors )
1- Go ools 1.
2 Your First Program 15
21 4o% to 5ead a Go Program 1*
3 Types 23
.1 !umbers 2-
.2 &trings 2)
.. 'ooleans .1
4 Variables 35
-1 4o% to !ame a 6ariable .)-2 &cope -0
-. Constants -.
-- De"ining 7ultiple 6ariables --
-/ An 3xample Program -/
5 Control Structures 4
/1 or -+
/2 I" /1
/. &%itch //
! "rrays# Slices and $aps 5%
81 Arrays /+
82 &lices 8-
8. 7aps 8*
Functions !
*1 9our &econd unction **
*2 5eturning 7ultiple 6alues +2
*. 6ariadic unctions +2
-
8/22/2019 go Language book
4/165
*- Closure +-
*/ 5ecursion +8
*8 De"er$ Panic : 5ecover ++
% Pointers &2
+1 he ; and : operators ).
+2 ne% )-
& Structs and 'nter(aces &
)1 &tructs )+
)2 7ethods 101
). Inter"aces 10-
1) Concurrency 1)%
101 Goroutines 10+
102 Channels 111
11 Pac*ages 12)
111 Creating Pac#ages 121
112 Documentation 12-
12 Testing 12
13 T+e Core Pac*ages 132
1.1 &trings 1.2
1.2 Input < =utput 1.-
1.. iles : olders 1./
1.- 3rrors 1-0
1./ Containers : &ort 1-1
1.8 4ashes : Cryptography 1--
1.* &ervers 1-*
1.+ Parsing Command ine Arguments 1//
1.) &ynchroni>ation Primitives 1/8
14 ,e-t Steps 15&
1-1 &tudy the 7asters 1/)
1-2 7a#e &omething 1801-. eam ?p 181
-
8/22/2019 go Language book
5/165
1 Getting Started
Computer programming is the art$ cra"t and science o"
%riting programs %hich de"ine ho% computers operatehis boo# %ill teach you ho% to %rite computer pro,
grams using a programming language designed by
Google named Go
Go is a general purpose programming language %ith
advanced "eatures and a clean syntax 'ecause o" its
%ide availability on a variety o" plat"orms$ its robust
%ell,documented common library$ and its "ocus on
good so"t%are engineering principles$ Go is an ideal
language to learn as your "irst programming language
he process %e use to %rite so"t%are using Go @and
most programming languages is "airly straight"or,
%ard(
1 Gather reBuirements
2 ind a solution
. rite source code to implement the solution
1
-
8/22/2019 go Language book
6/165
Getting Started 2
- Compile the source code into an executable
/ 5un and test the program to ma#e sure it %or#s
his process is iterative @meaning its done many
times and the steps usually overlap 'ut be"ore %e
%rite our "irst program in Go there are a "e% prereBui,
site concepts %e need to understand
1.1 Files and Folders
A "ile is a collection o" data stored as a unit %ith a
name 7odern operating systems @li#e indo%s or
7ac =& contain millions o" "iles %hich store a large
variety o" di""erent types o" in"ormation E everything
"rom text documents to executable programs to multi,
media "iles
All "iles are stored in the same %ay on a computer(
they all have a name$ a de"inite si>e @measured in
bytes and an associated type ypically the "ileFs typeis signi"ied by the "ileFs extension E the part o" the "ile
name that comes a"ter the last . or example a "ile
%ith the name hello.txthas the extension txt%hich
is used to represent textual data
olders @also called directories are used to group "ilestogether hey can also contain other "olders =n in,
-
8/22/2019 go Language book
7/165
3 Getting Started
do%s "ile and "older paths @locations are represented
%ith the \ @bac#slash character$ "or example(C:\Users\john\example.txt example.txt is the "ile
name$ it is contained in the "older john$ %hich is itsel"
contained in the "older Users%hich is stored on drive C
@%hich represents the primary physical hard drive in
indo%s =n =& @and most other operating sys,
tems "ile and "older paths are represented %ith the /@"or%ard slash character$ "or example(
/Users/john/example.txt i#e on indo%s
example.txt is the "ile name$ it is contained in the
"older john$ %hich is in the "older Users ?nli#e in,
do%s$ =& does not speci"y a drive letter %here the "ile
is stored
-
8/22/2019 go Language book
8/165
Getting Started 4
/indo0s
=n indo%s "iles and "olders can be bro%sed using
indo%s 3xplorer @accessible by double,clic#ing 7y
ComputerH or typing %ine(
-
8/22/2019 go Language book
9/165
5 Getting Started
S
=n =& "iles and "olders can be bro%sed using inder
@accessible by clic#ing the inder icon E the "ace icon
in the lo%er le"t bar(
1.2 T+e Terminal
7ost o" the interactions %e have %ith computers today
are through sophisticated graphical user inter"aces
@G?Is e use #eyboards$ mice and touchscreens to
interact %ith visual buttons or other types o" controls
that are displayed on a screen
It %asnFt al%ays this %ay 'e"ore the G?I %e had the
terminal E a simpler textual inter"ace to the computer
-
8/22/2019 go Language book
10/165
Getting Started 6
%here rather than manipulating buttons on a screen
%e issued commands and received replies e had aconversation %ith the computer
And although it might appear that most o" the comput,
ing %orld has le"t behind the terminal as a relic o" the
past$ the truth is that the terminal is still the "unda,
mental user inter"ace used by most programming lan,
guages on most computers he Go programming lan,
guage is no di""erent$ and so be"ore %e %rite a program
in Go %e need to have a rudimentary understanding o"
ho% a terminal %or#s
/indo0s
In indo%s the terminal @also #no%n as the command
line can be brought up by typing the %indo%s #ey r
@hold do%n the %indo%s #ey then press r$ typing
cmd.exeand hitting enter 9ou should see a blac# %in,
do% appear that loo#s li#e this(
-
8/22/2019 go Language book
11/165
7 Getting Started
'y de"ault the command line starts in your home di,
rectory @In my case this is C:\Users\caleb 9ou issue
commands by typing them in and hitting enter ry
entering the command dir$ %hich lists the contents o"
a directory 9ou should see something li#e this(
C:\Users\caleb>dirVolume in drive C has no label.Volume Serial Number is B!"#!$"
ollo%ed by a list o" the "iles and "olders contained in
your home directory 9ou can change directories by us,ing the command cd or example you probably have a
"older called %es&top 9ou can see its contents by en,
tering cd %es&topand then entering dir o go bac# to
your home directory you can use the special directory
name ..@t%o periods next to each other( cd .. A sin,
gle period represents the current "older @#no%n as the%or#ing "older$ so cd .doesnFt do anything here are
-
8/22/2019 go Language book
12/165
Getting Started 8
a lot more commands you can use$ but this should be
enough to get you started
S
In =& the terminal can be reached by going to inder
J Applications J ?tilities J erminal 9ou should
see a %indo% li#e this(
'y de"ault the terminal starts in your home directory
@In my case this is /Users/caleb 9ou issue commands
by typing them in and hitting enter ry entering the
command ls$ %hich lists the contents o" a directory
9ou should see something li#e this(
-
8/22/2019 go Language book
13/165
9 Getting Started
caleb#min:' caleb( ls
%es&top %o)nloads *ovies +ictures%ocuments ,ibrar- *usic +ublic
hese are the "iles and "olders contained in your home
directory @in this case there are no "iles 9ou can
change directories using the cdcommand or example
you probably have a "older called %es&top 9ou can seeits contents by entering cd %es&topand then entering
ls o go bac# to your home directory you can use the
special directory name .. @t%o periods next to each
other( cd .. A single period represents the current
"older @#no%n as the %or#ing "older$ so cd .doesnFt do
anything here are a lot more commands you can use$
but this should be enough to get you started
1.3 Te-t ditors
he primary tool programmers use to %rite so"t%are is
a text editor ext editors are similar to %ord process,
ing programs @7icroso"t ord$ =pen =""ice$ K but un,
li#e such programs they donFt do any "ormatting$ @!o
bold$ italic$ K instead they operate only on plain text
'oth =& and indo%s come %ith text editors but
they are highly limited and I recommend installing a
better one
o ma#e the installation o" this so"t%are easier an in,
-
8/22/2019 go Language book
14/165
Getting Started 10
staller is available at the boo#Fs %ebsite(
http://))).olan#boo&.com/ his installer %ill in,stall the Go tool suite$ setup environmental variables
and install a text editor
/indo0s
or %indo%s the installer %ill install the &cite text ed,
itor 9ou can open it by going to &tart J All Programs
J Go J &cite 9ou should see something li#e this(
he text editor contains a large %hite text area %here
text can be entered o the le"t o" this text area you
can see the line numbers At the bottom o" the %indo%
-
8/22/2019 go Language book
15/165
11 Getting Started
is a status bar %hich displays in"ormation about the
"ile and your current location in it @right no% it saysthat %e are on line 1$ column 1$ text is being inserted
normally$ and %e are using %indo%s,style ne%lines
9ou can open "iles by going to ile J =pen and bro%s,
ing to your desired "ile iles can be saved by going to
ile J &ave or ile J &ave As
As you %or# in a text editor it is use"ul to learn #ey,
board shortcuts he menus list the shortcuts to their
right 4ere are a "e% o" the most common(
Ctrl & E save the current "ile
Ctrl E cut the currently selected text @remove it
and put it in your clipboard so it can be pasted later
Ctrl C E copy the currently selected text
Ctrl 6 E paste the text currently in the clipboard
?se the arro% #eys to navigate$ 4ome to go to the
beginning o" the line and 3nd to go to the end o" the
line
4old do%n shi"t %hile using the arro% #eys @or
4ome and 3nd to select text %ithout using the
mouse
Ctrl E brings up a "ind in "ile dialog that you can
use to search the contents o" a "ile
-
8/22/2019 go Language book
16/165
Getting Started 12
S
or =& the installer installs the ext rangler text
editor(
i#e &cite on indo%s ext rangler contains a large
%hite area %here text is entered iles can be opened
by going to ile J =pen iles can be saved by going to
ile J &ave or ile J &ave As 4ere are some use"ul
#eyboard shortcuts( @Command is the #ey
-
8/22/2019 go Language book
17/165
13 Getting Started
Command & E save the current "ile
Command E cut the currently selected text @re,move it and put it in your clipboard so it can be
pasted later
Command C E copy the currently selected text
Command 6 E paste the text currently in the clip,
board
?se the arro% #eys to navigate Command E brings up a "ind in "ile dialog that
you can use to search the contents o" a "ile
1.4 Go Tools
Go is a compiled programming language$ %hich means
source code @the code you %rite is translated into a
language that your computer can understand here,
"ore be"ore %e can %rite a Go program$ %e need the Go
compiler
he installer %ill setup Go "or you automatically e
%ill be using version 1 o" the language @7ore in"orma,
tion can be "ound at http://))).olan.or
etFs ma#e sure everything is %or#ing =pen up a ter,
minal and type the "ollo%ing(
o version
-
8/22/2019 go Language book
18/165
Getting Started 14
9ou should see the "ollo%ing(
o version o$..
9our version number may be slightly di""erent I" you
get an error about the command not being recogni>ed
try restarting your computer
he Go tool suite is made up o" several di""erent com,
mands and sub,commands A list o" those commands is
available by typing(
o help
e %ill see ho% they are used in subseBuent chapters
-
8/22/2019 go Language book
19/165
2 Your First Program
raditionally the "irst program you %rite in any pro,
gramming language is called a 4ello orldH programE a program that simply outputs 0ello 1orldto your
terminal etFs %rite one using Go
irst create a ne% "older %here %e can store our pro,
gram he installer you used in chapter 1 created a
"older in your home directory named 2o Create a
"older named '/2o/src/olan#boo&/chapter @here
'means your home directory rom the terminal you
can do this by entering the "ollo%ing commands(
m&dir 2o/src/olan#boo&m&dir 2o/src/olan#boo&/chapter
?sing your text editor type in the "ollo%ing(
15
-
8/22/2019 go Language book
20/165
Your First Program 16
pac&ae main
import 34mt3
// this is a comment
4unc main56 7 4mt.+rintln530ello 1orld368
7a#e sure your "ile is identical to %hat is sho%n here
and save it as main.o in the "older %e Lust created
=pen up a ne% terminal and type in the "ollo%ing(
cd 2o/src/olan#boo&/chapter
o run main.o
9ou should see 0ello 1orlddisplayed in your termi,
nal he o runcommand ta#es the subseBuent "iles
@separated by spaces$ compiles them into an exe,
cutable saved in a temporary directory and then runs
the program I" you didnFt see 0ello 1orld displayed
you may have made a mista#e %hen typing in the pro,
gram he Go compiler %ill give you hints about %here
the mista#e lies i#e most compilers$ the Go compiler
is extremely pedantic and has no tolerance "or mis,
ta#es
-
8/22/2019 go Language book
21/165
17 Your First Program
2.1 o0 to ead a Go Program
etFs loo# at this program in more detail Go programs
are read top to bottom$ le"t to right @li#e a boo# he
"irst line says this(
pac&ae main
his is #no% as a pac#age declarationH 3very Go pro,
gram must start %ith a pac#age declaration Pac#ages
are GoFs %ay o" organi>ing and reusing code here are
t%o types o" Go programs( executables and libraries
3xecutable applications are the #inds o" programs that
%e can run directly "rom the terminal @in indo%sthey end %ith .exe ibraries are collections o" code
that %e pac#age together so that %e can use them in
other programs e %ill explore libraries in more de,
tail later$ "or no% Lust ma#e sure to include this line in
any program you %rite
he next line is a blan# line Computers represent
ne%lines %ith a special character @or several charac,
ters !e%lines$ spaces and tabs are #no%n as %hite,
space @because you canFt see them Go mostly doesnFt
care about %hitespace$ %e use it to ma#e programs
easier to read @9ou could remove this line and the pro,
gram %ould behave in exactly the same %ay
-
8/22/2019 go Language book
22/165
Your First Program 18
hen %e see this(
import 34mt3
he import#ey%ord is ho% %e include code "rom other
pac#ages to use %ith our program he 4mt pac#age
@shorthand "or "ormat implements "ormatting "or in,
put and output Given %hat %e Lust learned about
pac#ages %hat do you thin# the 4mt pac#ageFs "iles
%ould contain at the top o" themM
!otice that 4mtabove is surrounded by double Buotes
he use o" double Buotes li#e this is #no%n as a string
literalH %hich is a type o" expressionH In Go stringsrepresent a seBuence o" characters @letters$ numbers$
symbols$ K o" a de"inite length &trings are described
in more detail in the next chapter$ but "or no% the im,
portant thing to #eep in mind is that an opening 3
character must eventually be "ollo%ed by another 3
character and anything in bet%een the t%o is includedin the string @he 3character itsel" is not part o" the
string
he line that starts %ith //is #no%n as a comment
Comments are ignored by the Go compiler and are
there "or your o%n sa#e @or %hoever pic#s up thesource code "or your program Go supports t%o di""er,
-
8/22/2019 go Language book
23/165
19 Your First Program
ent styles o" comments( //comments in %hich all the
text bet%een the //and the end o" the line is part o"the comment and /9 9/comments %here everything
bet%een the 9s is part o" the comment @And may in,
clude multiple lines
A"ter this you see a "unction declaration(
4unc main56 7 4mt.+rintln530ello 1orld368
unctions are the building bloc#s o" a Go program
hey have inputs$ outputs and a series o" steps called
statements %hich are executed in order All "unctions
start %ith the #ey%ord 4unc"ollo%ed by the name o"
the "unction @mainin this case$ a list o" >ero or more
parametersH surrounded by parentheses$ an optional
return type and a bodyH %hich is surrounded by curly
braces his "unction has no parameters$ doesnFt re,
turn anything and has only one statement he name
mainis special because itFs the "unction that gets called
%hen you execute the program
he "inal piece o" our program is this line(
4mt.+rintln530ello 1orld36
-
8/22/2019 go Language book
24/165
Your First Program 20
his statement is made o" three components irst %e
access another "unction inside o" the 4mt pac#agecalled +rintln @thatFs the 4mt.+rintln piece$ +rintln
means Print ine hen %e create a ne% string that
contains 0ello 1orldand invo#e @also #no%n as call or
execute that "unction %ith the string as the "irst and
only argument
At this point %eFve already seen a lot o" ne% terminol,
ogy and you may be a bit over%helmed &ometimes its
help"ul to deliberately read your program out loud
=ne reading o" the program %e Lust %rote might go
li#e this(
Create a ne% executable program$ %hich re"erences
the 4mt library and contains one "unction called
main hat "unction ta#es no arguments$ doesnFt re,
turn anything and does the "ollo%ing( Access the
+rintln "unction contained inside o" the 4mt pac#,
age and invo#e it using one argument E the string
0ello 1orld
he +rintln "unction does the real %or# in this pro,
gram 9ou can "ind out more about it by typing the "ol,
lo%ing in your terminal(
odoc 4mt +rintln
-
8/22/2019 go Language book
25/165
21 Your First Program
Among other things you should see this(
+rintln 4ormats usin the de4ault 4ormats 4orits operands and )rites to standard output.Spaces are al)a-s added bet)een operands and ane)line is appended. t returns the number o4b-tes )ritten and an- )rite error encountered.
Go is a very %ell documented programming language
but this documentation can be di""icult to understand
unless you are already "amiliar %ith programming lan,
guages !evertheless the odoccommand is extremely
use"ul and a good place to start %henever you have a
Buestion
'ac# to the "unction at hand$ this documentation is
telling you that the +rintln "unction %ill send %hat,
ever you give to it to standard output E a name "or the
output o" the terminal you are %or#ing in his "unc,
tion is %hat causes 0ello 1orldto be displayed
In the next chapter %e %ill explore ho% Go stores and
represents things li#e 0ello 1orldby learning about
types
-
8/22/2019 go Language book
26/165
Your First Program 22
Problems
1 hat is %hitespaceM
2 hat is a commentM hat are the t%o %ays o"
%riting a commentM
. =ur program began %ith pac&ae main hat
%ould the "iles in the 4mtpac#age begin %ithM
- e used the +rintln"unction de"ined in the 4mt
pac#age I" %e %anted to use the ;xit "unction
"rom the ospac#age %hat %ould %e need to doM
/ 7odi"y the program %e %rote so that instead o"
printing 0ello 1orld it prints 0ello< m- name
is"ollo%ed by your name
-
8/22/2019 go Language book
27/165
3 Types
In the last chapter %e used the data type string to
store 0ello 1orld Data types categori>e a set o" re,lated values$ describe the operations that can be done
on them and de"ine the %ay they are stored &ince
types can be a di""icult concept to grasp %e %ill loo# at
them "rom a couple di""erent perspectives be"ore %e
see ho% they are implemented in Go
Philosophers sometimes ma#e a distinction bet%een
types and to#ens or example suppose you have a dog
named 7ax 7ax is the to#en @a particular instance or
member and dog is the type @the general concept
DogH or dognessH describes a set o" properties that all
dogs have in common Although oversimplistic %e
might reason li#e this( All dogs have - legs$ 7ax is a
dog$ there"ore 7ax has - legs ypes in programming
languages %or# in a similar %ay( All strings have a
length$ x is a string$ there"ore x has a length
In mathematics %e o"ten tal# about sets or example(
@the set o" all real numbers or @the set o" all natu,ral numbers 3ach member o" these sets shares prop,
23
-
8/22/2019 go Language book
28/165
Types 24
erties %ith all the other members o" the set or exam,
ple all natural numbers are associative( "or all natu,ral numbers a$ b$ and c$ a @b c N @a b c and a O
@b O c N @a O b O cH In this %ay sets are similar to
types in programming languages since all the values o"
a particular type share certain properties
Go is a statically typed programming language his
means that variables al%ays have a speci"ic type and
that type cannot change &tatic typing may seem cum,
bersome at "irst 9ouFll spend a large amount o" your
time Lust trying to "ix your program so that it "inally
compiles 'ut types help us reason about %hat our pro,
gram is doing and catch a %ide variety o" common mis,
ta#es
Go comes %ith several built,in data types %hich %e
%ill no% loo# at in more detail
3.1 ,umbers
Go has several di""erent types to represent numbers
Generally %e split numbers into t%o di""erent #inds(
integers and "loating,point numbers
'ntegers
Integers E li#e their mathematical counterpart E are
-
8/22/2019 go Language book
29/165
25 Types
numbers %ithout a decimal component @K$ ,.$ ,2$ ,1$
0$ 1$ K ?nli#e the base,10 decimal system %e use torepresent numbers$ computers use a base,2 binary sys,
tem
=ur system is made up o" 10 di""erent digits =nce
%eFve exhausted our available digits %e represent
larger numbers by using 2 @then .$ -$ /$ K digits put
next to each other or example the number a"ter ) is
10$ the number a"ter )) is 100 and so on Computers
do the same$ but they only have 2 digits instead o" 10
&o counting loo#s li#e this( 0$ 1$ 10$ 11$ 100$ 101$ 110$
111 and so on he other di""erence bet%een the num,
ber system %e use and the one computers use is that
all o" the integer types have a de"inite si>e hey only
have room "or a certain number o" digits &o a - bit in,
teger might loo# li#e this( 0000$ 0001$ 0010$ 0011$
0100 3ventually %e run out o" space and most com,
puters Lust %rap around to the beginning @hich can
result in some very strange behavior
GoFs integer types are( uint=$ uint$$ uint?$ uint@$
int=$ int$$ int?and int@.+$ 18$ .2 and 8- tell us
ho% many bits each o" the types use uintmeans un,
signed integerH %hile intmeans signed integerH ?n,
signed integers only contain positive numbers @or
>ero In addition there t%o alias types( b-te%hich isthe same as uint= and rune %hich is the same as
-
8/22/2019 go Language book
30/165
Types 26
int? 'ytes are an extremely common unit o" mea,
surement used on computers @1 byte N + bits$ 102-bytes N 1 #ilobyte$ 102- #ilobytes N 1 megabyte$ K
and there"ore GoFs b-tedata type is o"ten used in the
de"inition o" other types here are also . machine de,
pendent integer types( uint$ intand uintptr hey are
machine dependent because their si>e depends on the
type o" architecture you are using
Generally i" you are %or#ing %ith integers you should
Lust use the inttype
Floating Point ,umbers
loating point numbers are numbers that contain a
decimal component @real numbers @12.-$ 12.-$
0000012.-$ 12.-0000 heir actual representation on
a computer is "airly complicated and not really neces,
sary in order to #no% ho% to use them &o "or no% %e
need only #eep the "ollo%ing in mind(
1 loating point numbers are inexact =ccasion,
ally it is not possible to represent a number or
example computing $.$ # .AA results in
.$= E A number extremely
close to %hat %e %ould expect$ but not exactly
the same
-
8/22/2019 go Language book
31/165
27 Types
2 i#e integers "loating point numbers have a cer,
tain si>e @.2 bit or 8- bit ?sing a larger si>ed"loating point number increases itFs precision
@ho% many digits it can represent
. In addition to numbers there are several other
values %hich can be represented( not a num,
berH @NaN$ "or things li#e / and positive and
negative in"inity @and D
Go has t%o "loating point types( 4loat? and 4loat@
@also o"ten re"erred to as single precision and double
precision respectively as %ell as t%o additional types
"or representing complex numbers @numbers %ith
imaginary parts( complex@and complex$= Generally
%e should stic# %ith 4loat@%hen %or#ing %ith "loat,
ing point numbers
-ample
etFs %rite an example program using numbers irstcreate a "older called chapter?and ma#e a main.o"ile
containing the "ollo%ing(
-
8/22/2019 go Language book
32/165
Types 28
pac&ae main
import 34mt3
4unc main56 7 4mt.+rintln53$ $ E3< $ $68
I" you run the program and you should see this(
( o run main.o$ $ E
!otice that this program is very similar to the pro,
gram %e %rote in chapter 2 It contains the same pac#,age line$ the same import line$ the same "unction dec,
laration and uses the same +rintln"unction his time
instead o" printing the string 0ello 1orld%e print the
string $ $ E"ollo%ed by the result o" the expression
$ $ his expression is made up o" three parts( the
numeric literal $@%hich is o" type int$ the operator@%hich represents addition and another numeric lit,
eral $ etFs try the same thing using "loating point
numbers(
4mt.+rintln53$ $ E3< $. $.6
!otice that %e use the .to tell Go that this is a "loat,
-
8/22/2019 go Language book
33/165
29 Types
ing point number instead o" an integer 5unning this
program %ill give you the same result as be"ore
In addition to addition Go has several other operators(
addition
# subtraction
9 multiplication
/ division
F remainder
3.2 Strings
As %e sa% in chapter 2 a string is a seBuence o" char,
acters %ith a de"inite length used to represent text Go
strings are made up o" individual bytes$ usually one
"or each character @Characters "rom other languages
li#e Chinese are represented by more than one byte
&tring literals can be created using double Buotes
30ello 1orld3or bac# tic#s G0ello 1orldG he di""er,
ence bet%een these is that double Buoted strings can,
not contain ne%lines and they allo% special escape se,
Buences or example \ngets replaced %ith a ne%line
and \tgets replaced %ith a tab character
-
8/22/2019 go Language book
34/165
Types 30
&everal common operations on strings include "inding
the length o" a string( len530ello 1orld36$ accessingan individual character in the string( 30ello
1orld3H$I$ and concatenating t%o strings together(
30ello 3 31orld3 etFs modi"y the program %e cre,
ated earlier to test these out(
pac&ae main
import 34mt3
4unc main56 7 4mt.+rintln5len530ello 1orld366 4mt.+rintln530ello 1orld3H$I6 4mt.+rintln530ello 3 31orld36
8
A "e% things to notice(
1 A space is also considered a character$ so the
stringFs length is 11 not 10 and the . rdline has
30ello 3instead o" 30ello3
2 &trings are indexedH starting at 0 not 1 H$I
gives you the 2ndelement not the 1st Also notice
that you see $$instead o" e%hen you run this
program his is because the character is repre,
sented by a byte @remember a byte is an
integer
-
8/22/2019 go Language book
35/165
31 Types
=ne %ay to thin# about indexing %ould be tosho% it li#e this instead( 30ello 1orld3$ 9ouFd
read that as he string 4ello orld sub 1$H
he string 4ello orld at 1H or he second
character o" the string 4ello orldH
. Concatenation uses the same symbol as addi,
tion he Go compiler "igures out %hat to do
based on the types o" the arguments &ince both
sides o" the are strings the compiler assumes
you mean concatenation and not addition @Ad,
dition is meaningless "or strings
3.3 6ooleans
A boolean value @named a"ter George 'oole is a spe,
cial 1 bit integer type used to represent true and "alse
@or on and o"" hree logical operators are used %ith
boolean values(
JJ and
KK or
L not
4ere is an example program sho%ing ho% they can be
-
8/22/2019 go Language book
36/165
Types 32
used(
4unc main56 7 4mt.+rintln5true JJ true6 4mt.+rintln5true JJ 4alse6 4mt.+rintln5true KK true6 4mt.+rintln5true KK 4alse6 4mt.+rintln5Ltrue68
5unning this program should give you(
( o run main.otrue4alse
truetrue4alse
e usually use truth tables to de"ine ho% these opera,
tors %or#(
-pression Value
true JJ true true
true JJ 4alse 4alse
4alse JJ true 4alse
4alse JJ 4alse 4alse
-
8/22/2019 go Language book
37/165
33 Types
-pression Value
true KK true true
true KK 4alse true
4alse KK true true
4alse KK 4alse 4alse
-pression Value
Ltrue 4alse
L4alse true
hese are the simplest types included %ith Go and
"orm the "oundation "rom %hich all later types arebuilt
-
8/22/2019 go Language book
38/165
Types 34
Problems
1 4o% are integers stored on a computerM
2 e #no% that @in base 10 the largest 1 digit
number is ) and the largest 2 digit number is
)) Given that in binary the largest 2 digit num,
ber is 11 @.$ the largest . digit number is 111
@* and the largest - digit number is 1111 @1/
%hatFs the largest + digit numberM @int( 101,1 N
) and 102,1 N ))
. Although overpo%ered "or the tas# you can use
Go as a calculator rite a program that com,
putes ?$?" M @@"$and prints it to the ter,
minal @?se the 9operator "or multiplication
- hat is a stringM 4o% do you "ind its lengthM
/ hatFs the value o" the expression 5true JJ
4alse6 KK 54alse JJ true6 KK L54alse JJ4alse6M
-
8/22/2019 go Language book
39/165
4 Variables
?p until no% %e have only seen programs that use lit,
eral values @numbers$ strings$ etc but such programsarenFt particularly use"ul o ma#e truly use"ul pro,
grams %e need to learn t%o ne% concepts( variables
and control "lo% statements his chapter %ill explore
variables in more detail
A variable is a storage location$ %ith a speci"ic type
and an associated name etFs change the program %e
%rote in chapter 2 so that it uses a variable(
pac&ae main
import 34mt3
4unc main56 7 var x strin E 30ello 1orld3 4mt.+rintln5x68
!otice that the string literal "rom the original program
still appears in this program$ but rather than send itdirectly to the +rintln"unction %e assign it to a vari,
35
-
8/22/2019 go Language book
40/165
!aria"#es 36
able instead 6ariables in Go are created by "irst using
the var#ey%ord$ then speci"ying the variable name @x$the type @strin and "inally assigning a value to the
variable @0ello 1orld he last step is optional so an
alternative %ay o" %riting the program %ould be li#e
this(
pac&ae main
import 34mt3
4unc main56 7 var x strin x E 30ello 1orld3 4mt.+rintln5x6
8
6ariables in Go are similar to variables in algebra but
there are some subtle di""erences(
irst %hen %e see the Esymbol %e have a tendency to
read that as x eBuals the string 4ello orldH hereFsnothing %rong %ith reading our program that %ay$ but
itFs better to read it as x ta#es the string 4ello orldH
or x is assigned the string 4ello orldH his distinc,
tion is important because @as their name %ould sug,
gest variables can change their value throughout the
li"etime o" a program ry running the "ollo%ing(
-
8/22/2019 go Language book
41/165
37 !aria"#es
pac&ae main
import 34mt3
4unc main56 7 var x strin x E 34irst3 4mt.+rintln5x6 x E 3second3
4mt.+rintln5x68
In "act you can even do this(
var x strinx E 34irst 34mt.+rintln5x6x E x 3second34mt.+rintln5x6
his program %ould be nonsense i" you read it li#e an
algebraic theorem 'ut it ma#es sense i" you are care,
"ul to read the program as a list o" commands hen%e see x E x 3second3%e should read it as assign
the concatenation o" the value o" the variable x and the
string literal second to the variable xH he right side
o" the Eis done "irst and the result is then assigned to
the le"t side o" the E
he x E x -"orm is so common in programming that
-
8/22/2019 go Language book
42/165
!aria"#es 38
Go has a special assignment statement( E e could
have %ritten x E x 3second3as x E 3second3and it%ould have done the same thing @=ther operators can
be used the same %ay
Another di""erence bet%een Go and algebra is that %e
use a di""erent symbol "or eBuality( EE @%o eBual
signs next to each other EEis an operator li#e and itreturns a boolean or example(
var x strin E 3hello3 var - strin E 3)orld3 4mt.+rintln5x EE -6
his program should print 4alsebecause hellois not
the same as )orld =n the other hand(
var x strin E 3hello3 var - strin E 3hello3 4mt.+rintln5x EE -6
his %ill print truebecause the t%o strings are the
same
&ince creating a ne% variable %ith a starting value is
so common Go also supports a shorter statement(
-
8/22/2019 go Language book
43/165
39 !aria"#es
x :E 30ello 1orld3
!otice the :be"ore the Eand that no type %as speci,
"ied he type is not necessary because the Go compiler
is able to in"er the type based on the literal value you
assign the variable @&ince you are assigning a string
literal$ x is given the type strin he compiler can
also do in"erence %ith the varstatement(
var x E 30ello 1orld3
he same thing %or#s "or other types(
x :E " 4mt.+rintln5x6
Generally you should use this shorter "orm %henever
possible
4.1 o0 to ,ame a Variable
!aming a variable properly is an important part o"
so"t%are development !ames must start %ith a letter
and may contain letters$ numbers or the @underscore
symbol he Go compiler doesnFt care %hat you name a
variable so the name is meant "or your @and others
-
8/22/2019 go Language book
44/165
!aria"#es 40
bene"it Pic# names %hich clearly describe the vari,
ableFs purpose &uppose %e had the "ollo%ing(
x :E 3*ax3 4mt.+rintln53*- doOs name is3< x6
In this case x is not a very good name "or a variable A
better name %ould be(
name :E 3*ax3 4mt.+rintln53*- doOs name is3< name6
or even(
dosName :E 3*ax3 4mt.+rintln53*- doOs name is3< dosName6
In this last case %e use a special %ay to represent mul,
tiple %ords in a variable name #no%n as lo%er camel
case @also #no% as mixed case$ bumpy caps$ camel
bac# or hump bac# he "irst letter o" the "irst %ord is
lo%ercase$ the "irst letter o" the subseBuent %ords is
uppercase and all the other letters are lo%ercase
4.2 Scope
Going bac# to the program %e sa% at the beginning o"
-
8/22/2019 go Language book
45/165
41 !aria"#es
the chapter(
pac&ae main
import 34mt3
4unc main56 7 var x strin E 30ello 1orld3 4mt.+rintln5x6
8
Another %ay o" %riting this program %ould be li#e
this(
pac&ae main
import 34mt3
var x strin E 30ello 1orld3
4unc main56 7 4mt.+rintln5x68
!otice that %e moved the variable outside o" the main
"unction his means that other "unctions can access
this variable(
-
8/22/2019 go Language book
46/165
!aria"#es 42
var x strin E 30ello 1orld3
4unc main56 7 4mt.+rintln5x68
4unc 456 7 4mt.+rintln5x68
he 4"unction no% has access to the xvariable !o%
suppose that %e %rote this instead(
4unc main56 7 var x strin E 30ello 1orld3
4mt.+rintln5x68
4unc 456 7 4mt.+rintln5x68
I" you run this program you should see an error(
.\main.o:$$: unde4ined: x
he compiler is telling you that the xvariable inside o"
the 4"unction doesnFt exist It only exists inside o" the
main"unction he range o" places %here you are al,lo%ed to use xis called the s$opeo" the variable Ac,
-
8/22/2019 go Language book
47/165
43 !aria"#es
cording to the language speci"ication Go is lexically
scoped using bloc#sH 'asically this means that thevariable exists %ithin the nearest curly braces 7 8 @a
bloc# including any nested curly braces @bloc#s$ but
not outside o" them &cope can be a little con"using at
"irst as %e see more Go examples it should become
more clear
4.3 Constants
Go also has support "or constants Constants are basi,
cally variables %hose values cannot be changed later
hey are created in the same %ay you create variables
but instead o" using the var#ey%ord %e use the const
#ey%ord(
pac&ae main
import 34mt3
4unc main56 7
const x strin E 30ello 1orld3 4mt.+rintln5x68
his(
-
8/22/2019 go Language book
48/165
!aria"#es 44
const x strin E 30ello 1orld3
x E 3Some other strin3
5esults in a compile,time error(
.\main.o:P: cannot assin to x
Constants are a good %ay to reuse common values in a
program %ithout %riting them out each time or ex,
ample +iin the mathpac#age is de"ined as a constant
4.4 7e(ining $ultiple Variables
Go also has another shorthand %hen you need to de,
"ine multiple variables(
var 5 a E " b E $
c E $"6
?se the #ey%ord var @or const "ollo%ed by parenthe,
ses %ith each variable on its o%n line
-
8/22/2019 go Language book
49/165
45 !aria"#es
4.5 "n -ample Program
4ereFs an example program %hich ta#es in a number
entered by the user and doubles it(
pac&ae main
import 34mt3
4unc main56 74mt.+rint53;nter a number: 36var input [email protected]< Jinput6
output :E input 9
4mt.+rintln5output68
e use another "unction "rom the 4mtpac#age to read
the user input @Scan4 Jinput%ill be explained in a
later chapter$ "or no% all %e need to #no% is that Scan4
"ills input %ith the number %e enter
-
8/22/2019 go Language book
50/165
!aria"#es 46
Problems
1 hat are t%o %ays to create a ne% variableM
2 hat is the value o" x a"ter running(
x :E "Q x E $M
. hat is scope and ho% do you determine the
scope o" a variable in GoM
- hat is the di""erence bet%een varand constM
/ ?sing the example program as a starting point$
%rite a program that converts "rom ahrenheit
into Celsius @C E 5! # ?6 9 "/A
8 rite another program that converts "rom "eet
into meters @$ 4t E .?@= m
-
8/22/2019 go Language book
51/165
5 Control Structures
!o% that %e #no% ho% to use variables itFs time to
start %riting some use"ul programs irst letFs %rite aprogram that counts to 10$ starting "rom 1$ %ith each
number on its o%n line ?sing %hat %eFve learned so
"ar %e could %rite this(
pac&ae main
import 34mt3
4unc main56 7 4mt.+rintln5$6 4mt.+rintln56 4mt.+rintln5?6 4mt.+rintln5@6 4mt.+rintln5"6
4mt.+rintln56 4mt.+rintln5P6 4mt.+rintln5=6 4mt.+rintln5A6 4mt.+rintln5$68
=r this(
47
-
8/22/2019 go Language book
52/165
%ontro# Stru$tures 48
pac&ae main
import 34mt3
4unc main56 7 4mt.+rintln5G$?@"
P=A$G68
'ut both o" these programs are pretty tedious to %rite
hat %e need is a %ay o" doing something multiple
times
5.1 For
he 4orstatement allo%s us to repeat a list o" state,
ments @a bloc# multiple times 5e%riting our previous
program using a 4orstatement loo#s li#e this(
-
8/22/2019 go Language book
53/165
49 %ontro# Stru$tures
pac&ae main
import 34mt3
4unc main56 7 i :E $ 4or i RE $ 7 4mt.+rintln5i6 i E i $
88
irst %e create a variable called ithat %e use to store
the number %e %ant to print hen %e create a 4or
loop by using the #ey%ord 4or$ providing a conditional
expression %hich is either true or 4alse and "inally
supplying a bloc# to execute he "or loop %or#s li#e
this(
1 e evaluate @run the expression i RE $@i less
than or eBual to 10H I" this evaluates to true
then %e run the statements inside o" the bloc#
=ther%ise %e Lump to the next line o" our pro,
gram a"ter the bloc# @in this case there is noth,
ing a"ter the "or loop so %e exit the program
2 A"ter %e run the statements inside o" the bloc#
%e loop bac# to the beginning o" the "or state,
ment and repeat step 1
-
8/22/2019 go Language book
54/165
%ontro# Stru$tures 50
he i E i $ line is extremely important$ because
%ithout it i RE $%ould al%ays evaluate to trueandour program %ould never stop @hen this happens
this is re"erred to as an in"inite loop
As an exercise lets %al# through the program li#e a
computer %ould(
Create a variable named i%ith the value 1
Is i RE $M 9es
Print i
&et ito i $@ino% eBuals 2
Is i RE $M 9es
Print i &et ito i $@ino% eBuals .
K
&et ito i $@ino% eBuals 11
Is i RE $M !o
!othing le"t to do$ so exit
=ther programming languages have a lot o" di""erent
types o" loops @%hile$ do$ until$ "oreach$ K but Go only
has one that can be used in a variety o" di""erent %ays
he previous program could also have been %ritten
li#e this(
-
8/22/2019 go Language book
55/165
51 %ontro# Stru$tures
4unc main56 7
4or i :E $Q i RE $Q i 7 4mt.+rintln5i6 88
!o% the conditional expression also contains t%o other
statements %ith semicolons bet%een them irst %e
have the variable initiali>ation$ then %e have the con,
dition to chec# each time and "inally %e incrementH
the variable @adding 1 to a variable is so common that
%e have a special operator( &imilarly subtracting 1
can be done %ith ##
e %ill see additional %ays o" using the "or loop inlater chapters
5.2 '(
etFs modi"y the program %e Lust %rote so that instead
o" Lust printing the numbers 1,10 on each line it alsospeci"ies %hether or not the number is even or odd
i#e this(
-
8/22/2019 go Language book
56/165
%ontro# Stru$tures 52
$ odd
even? odd@ even" odd evenP odd= evenA odd
$ even
irst %e need a %ay o" determining %hether or not a
number is even or odd An easy %ay to tell is to divide
the number by 2 I" you have nothing le"t over then the
number is even$ other%ise itFs odd &o ho% do %e "ind
the remainder a"ter division in GoM e use the Foper,ator $ F eBuals $$ F eBuals $ ? F eBuals $and
so on
!ext %e need a %ay o" choosing to do di""erent things
based on a condition or that %e use the i4 state,
ment(
i4 i F EE 7 // even8 else 7 // odd8
An i4statement is similar to a 4orstatement in that it
-
8/22/2019 go Language book
57/165
53 %ontro# Stru$tures
has a condition "ollo%ed by a bloc# I" statements also
have an optional elsepart I" the condition evaluatesto truethen the bloc# a"ter the condition is run$ other,
%ise either the bloc# is s#ipped or i" the elsebloc# is
present that bloc# is run
I" statements can also have else i4parts(
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
he conditions are chec#ed top do%n and the "irst one
to result in true %ill have its associated bloc# exe,
cuted !one o" the other bloc#s %ill execute$ even i"
their conditions also pass @&o "or example the number
+ is divisible by both - and 2$ but the // divisible b-
@bloc# %ill never execute because the // divisible b-
bloc# is done "irst
Putting it all together %e have(
-
8/22/2019 go Language book
58/165
%ontro# Stru$tures 54
4unc main56 7
4or i :E $Q i RE $Q i 7 i4 i F EE 7
4mt.+rintln5i< 3even36 8 else 7 4mt.+rintln5i< 3odd36 8 88
etFs %al# through this program(
Create a variable io" type intand give it the value $
Is iless than or eBual to $M 9es( Lump to the bloc#
Is the remainder o" iQ eBual to M !o( Lump to the
elsebloc#
Print i"ollo%ed by odd
Increment i@the statement a"ter the condition
Is iless than or eBual to $M 9es( Lump to the bloc#
Is the remainder o" iQ eBual to M 9es( Lump to the
i4bloc#
Print i"ollo%ed by even
K
he remainder operator$ %hile rarely seen outside o"
elementary school$ turns out to be really use"ul %hen
programming 9ouFll see it turn up every%here "rom
>ebra striping tables to partitioning data sets
-
8/22/2019 go Language book
59/165
55 %ontro# Stru$tures
5.3 S0itc+
&uppose %e %anted to %rite a program that printed
the 3nglish names "or numbers ?sing %hat %eFve
learned so "ar %e might start by doing this(
i4 i EE 74mt.+rintln53ero36
8 else i4 i EE $ 7 4mt.+rintln53Tne368 else i4 i EE 7 4mt.+rintln53)o368 else i4 i EE ? 7 4mt.+rintln53hree368 else i4 i EE @ 7
4mt.+rintln53!our36
8 else i4 i EE " 7 4mt.+rintln53!ive368
&ince %riting a program in this %ay %ould be pretty
tedious Go provides another statement to ma#e this
easier( the s)itchstatement e can re%rite our pro,gram to loo# li#e this(
-
8/22/2019 go Language book
60/165
%ontro# Stru$tures 56
s)itch i 7
case : 4mt.+rintln53ero36case $: 4mt.+rintln53Tne36case : 4mt.+rintln53)o36case ?: 4mt.+rintln53hree36case @: 4mt.+rintln53!our36case ": 4mt.+rintln53!ive36de4ault: 4mt.+rintln53Un&no)n Number368
A s%itch statement starts %ith the #ey%ord s)itch"ol,
lo%ed by an expression @in this case i and then a se,
ries o" cases he value o" the expression is compared
to the expression "ollo%ing each case#ey%ord I" they
are eBuivalent then the statement@s "ollo%ing the :is
executed
i#e an i" statement each case is chec#ed top do%n
and the "irst one to succeed is chosen A s%itch also
supports a de"ault case %hich %ill happen i" none o"
the cases matches the value @Rind o" li#e the else in
an i" statement
hese are the main control "lo% statements Additional
statements %ill be explored in later chapters
-
8/22/2019 go Language book
61/165
57 %ontro# Stru$tures
Problems
1 hat does the "ollo%ing program print(
i :E $i4 i > $ 7 4mt.+rintln53Bi368 else 7
4mt.+rintln53Small368
2 rite a program that prints out all the numbers
evenly divisible by . bet%een 1 and 100 @.$ 8$ )$
etc
. rite a program that prints the numbers "rom 1
to 100 'ut "or multiples o" three print Si>>S in,
stead o" the number and "or the multiples o" "ive
print S'u>>S or numbers %hich are multiples
o" both three and "ive print Si>>'u>>S
-
8/22/2019 go Language book
62/165
! "rrays# Slices and $aps
In chapter . %e learned about GoFs basic types In this
chapter %e %ill loo# at three more built,in types( ar,rays$ slices and maps
!.1 "rrays
An array is a numbered seBuence o" elements o" a sin,
gle type %ith a "ixed length In Go they loo# li#e this(
var x H"Iint
x is an example o" an array %hich is composed o" /
ints ry running the "ollo%ing program(
58
-
8/22/2019 go Language book
63/165
59 &rrays' S#i$es and (aps
pac&ae main
import 34mt3
4unc main56 7var x H"IintxH@I E $4mt.+rintln5x6
8
9ou should see this(
H $I
xH@I E $should be read set the /thelement o" the
array x to 100H It might seem strange that xH@Irepre,
sents the /thelement instead o" the -thbut li#e strings$
arrays are indexed starting "rom 0 Arrays are ac,
cessed in a similar %ay e could change
4mt.+rintln5x6to 4mt.+rintln5xH@I6and %e %ould get
100
4ereFs an example program that uses arrays(
-
8/22/2019 go Language book
64/165
&rrays' S#i$es and (aps 60
4unc main56 7var x H"I4loat@xHI E A=xH$I E A?xHI E PPxH?I E =xH@I E =?
var total 4loat@ E 4or i :E Q i R "Q i 7
total E xHiI84mt.+rintln5total / "6
8
his program computes the average o" a series o" test
scores I" you run it you should see =. etFs %al#
through the program(
irst %e create an array o" length / to hold our test
scores$ then %e "ill up each element %ith a grade
!ext %e setup a "or loop to compute the total score
inally %e divide the total score by the number o" el,
ements to "ind the average
his program %or#s$ but Go provides some "eatures %e
can use to improve it irst these 2 parts( i R " and
total / "should thro% up a red "lag "or us &ay %e
-
8/22/2019 go Language book
65/165
61 &rrays' S#i$es and (aps
changed the number o" grades "rom / to 8 e %ould
also need to change both o" these parts It %ould bebetter to use the length o" the array instead(
var total 4loat@ E 4or i :E Q i R len5x6Q i 7
total E xHiI8
4mt.+rintln5total / len5x66
Go ahead and ma#e these changes and run the pro,
gram 9ou should get an error(
( o run tmp.o
command#line#aruments.\tmp.o:$A: invalid operation: total / "5mismatched t-pes 4loat@ and int6
he issue here is that len5x6and totalhave di""erent
types totalis a 4loat@%hile len5x6is an int &o %e
need to convert len5x6into a 4loat@(
4mt.+rintln5total / 4loat@5len5x666
his is an example o" a type conversion In general to
convert bet%een types you use the type name li#e a
"unction
-
8/22/2019 go Language book
66/165
&rrays' S#i$es and (aps 62
Another change to the program %e can ma#e is to use
a special "orm o" the "or loop(
var total 4loat@ E 4or i< value :E rane x 7
total E value84mt.+rintln5total / 4loat@5len5x666
In this "or loop irepresents the current position in the
array and valueis the same as xHiI e use the #ey,
%ord rane "ollo%ed by the name o" the variable %e
%ant to loop over
5unning this program %ill result in another error(
( o run tmp.o command#line#aruments.\tmp.o:$: i declared and not used
he Go compiler %onFt allo% you to create variablesthat you never use &ince %e donFt use iinside o" our
loop %e need to change it to this(
-
8/22/2019 go Language book
67/165
63 &rrays' S#i$es and (aps
var total 4loat@ E
4or < value :E rane x 7total E value
84mt.+rintln5total / 4loat@5len5x666
A single @underscore is used to tell the compiler that
%e donFt need this @In this case %e donFt need the iter,
ator variable
Go also provides a shorter syntax "or creating arrays(
x :E H"I4loat@7 A=< A?< PP< =< =? 8
e no longer need to speci"y the type because Go can
"igure it out &ometimes arrays li#e this can get too
long to "it on one line$ so Go allo%s you to brea# it up
li#e this(
x :E H"I4loat@7A=ero value "or the value type
@%hich "or strings is the empty string Although %ecould chec# "or the >ero value in a condition
@elementsH3Un3I EE 33 Go provides a better %ay(
name< o& :E elementsH3Un3I4mt.+rintln5name< o&6
Accessing an element o" a map can return t%o values
instead o" Lust one he "irst value is the result o" the
loo#up$ the second tells us %hether or not the loo#up
%as success"ul In Go %e o"ten see code li#e this(
i4 name< o& :E elementsH3Un3IQ o& 74mt.+rintln5name< o&6
8
irst %e try to get the value "rom the map$ then i" itFs
success"ul %e run the code inside o" the bloc#
i#e %e sa% %ith arrays there is also a shorter %ay to
create maps(
-
8/22/2019 go Language book
76/165
&rrays' S#i$es and (aps 72
elements :E mapHstrinIstrin7
303: 30-droen3e a map$ etc
or an exceptional condition that thereFs no easy %ay to
recover "rom @4ence the name panicH
-
8/22/2019 go Language book
95/165
91 Fun$tions
Problems
1 sumis a "unction %hich ta#es a slice o" numbers
and adds them together hat %ould its "unc,
tion signature loo# li#e in GoM
2 rite a "unction %hich ta#es an integer and
halves it and returns true i" it %as even or "alse
i" it %as odd or example hal45$6should return
5< 4alse6 and hal456 should return 5$ed domain speci"ic #no%ledge @"or
example( cryptography It is beyond the scope o" this
boo# to explain these underlying technologies
13.1 Strings
Go includes a large number o" "unctions to %or# %ith
strings in the strinspac#age(
132
-
8/22/2019 go Language book
137/165
133 Te %ore Pa$+ages
pac&ae main
import 534mt33strins3
6
4unc main56 74mt.+rintln5
// truestrins.Contains53test3< 3es36ed and supports
both the eaderand 1riterinter"aces 9ou can convert
it into a HIb-teby calling bu4.B-tes56 I" you only need
to read "rom a string you can also use the
strins.Ne)eader "unction %hich is more e""icient
than using a bu""er
13.3 Files 8 Folders
o open a "ile in Go use the Tpen"unction "rom the os
pac#age 4ere is an example o" ho% to read the con,tents o" a "ile and display them on the terminal(
-
8/22/2019 go Language book
140/165
Te %ore Pa$+ages 136
pac&ae main
import 534mt33os3
6
4unc main56 74ile< err :E os.Tpen53test.txt36
i4 err LE nil 7// handle the error herereturn
8de4er 4ile.Close56
// et the 4ile siZestat< err :E 4ile.Stat56i4 err LE nil 7
return8
// read the 4ilebs :E ma&e5HIb-te< stat.SiZe566< err E 4ile.ead5bs6i4 err LE nil 7
return
8
str :E strin5bs64mt.+rintln5str6
8
e use de4er 4ile.Close56right a"ter opening the "ile
to ma#e sure the "ile is closed as soon as the "unction
-
8/22/2019 go Language book
141/165
137 Te %ore Pa$+ages
completes 5eading "iles is very common$ so thereFs a
shorter %ay to do this(
pac&ae main
import 534mt33io/ioutil3
6
4unc main56 7bs< err :E ioutil.ead!ile53test.txt36i4 err LE nil 7
return8str :E strin5bs64mt.+rintln5str6
8
4ere is ho% %e can create a "ile(
-
8/22/2019 go Language book
142/165
Te %ore Pa$+ages 138
pac&ae main
import 53os3
6
4unc main56 74ile< err :E os.Create53test.txt36i4 err LE nil 7
// handle the error herereturn8de4er 4ile.Close56
4ile.1riteStrin53test368
o get the contents o" a directory %e use the same
os.Tpen"unction but give it a directory path instead o"
a "ile name hen %e call the eaddirmethod(
-
8/22/2019 go Language book
143/165
139 Te %ore Pa$+ages
pac&ae main
import 534mt33os3
6
4unc main56 7dir< err :E os.Tpen53.36
i4 err LE nil 7return8de4er dir.Close56
4ilen4os< err :E dir.eaddir5#$6i4 err LE nil 7
return8
4or < 4i :E rane 4ilen4os 74mt.+rintln54i.Name566
88
="ten %e %ant to recursively %al# a "older @read the
"olderFs contents$ all the sub,"olders$ all the sub,sub,
"olders$ K o ma#e this easier thereFs a 1al&"unction
provided in the path/4ilepathpac#age(
-
8/22/2019 go Language book
144/165
Te %ore Pa$+ages 140
pac&ae main
import 534mt33os33path/4ilepath3
6
4unc main56 7
4ilepath.1al&53.3< 4unc5path strin< in4oos.!ilen4o< err error6 error 74mt.+rintln5path6return nil
868
he "unction you pass to 1al& is called "or every "ile
and "older in the root "older @in this case .
13.4 rrors
Go has a built,in type "or errors that %e have already
seen @the errortype e can create our o%n errors by
using the Ne)"unction in the errorspac#age(
-
8/22/2019 go Language book
145/165
141 Te %ore Pa$+ages
pac&ae main
import 3errors3
4unc main56 7err :E errors.Ne)53error messae36
8
13.5 Containers 8 Sort
In addition to lists and maps Go has several more col,
lections available underneath the container pac#age
eFll ta#e a loo# at the container/listpac#age as an
example
=ist
he container/list pac#age implements a dou,
bly,lin#ed list A lin#ed list is a type o" data structure
that loo#s li#e this(
3ach node o" the list contains a value @1$ 2$ or . in this
case and a pointer to the next node &ince this is a
doubly,lin#ed list each node %ill also have pointers tothe previous node his list could be created by this
-
8/22/2019 go Language book
146/165
Te %ore Pa$+ages 142
program(
pac&ae main
import 534mt3 Q 3container/list36
4unc main56 7var x list.,istx.+ushBac&5$6
x.+ushBac&56x.+ushBac&5?6
4or e :E x.!ront56Q e LE nilQ eEe.Next56 74mt.+rintln5e.Value.5int66
88
he >ero value "or a ,istis an empty list @a 9,istcan
also be created using list.Ne) 6alues are appended
to the list using +ushBac& e loop over each item in
the list by getting the "irst element$ and "ollo%ing all
the lin#s until %e reach nil
Sort
he sort pac#age contains "unctions "or sorting arbi,
trary data here are several prede"ined sorting "unc,
tions @"or slices o" ints and "loats 4ereFs an example
"or ho% to sort your o%n data(
-
8/22/2019 go Language book
147/165
143 Te %ore Pa$+ages
pac&ae main
import 534mt3 Q 3sort36
t-pe +erson struct 7Name strinWe int
8
t-pe B-Name HI+erson
4unc 5this B-Name6 ,en56 int 7return len5this6
84unc 5this B-Name6 ,ess5i< j int6 bool 7
return thisHiI.Name R thisHjI.Name84unc 5this B-Name6 S)ap5i< j int6 7
thisHiI< thisHjI E thisHjI< thisHiI8
4unc main56 7&ids :E HI+erson7
73]ill3
-
8/22/2019 go Language book
148/165
Te %ore Pa$+ages 144
%e %ant to sort e then de"ine the . methods
&orting our list o" people is then as easy as casting the
list into our ne% type e could also sort by age by do,
ing this(
t-pe B-We HI+erson
4unc 5this B-We6 ,en56 int 7return len5this684unc 5this B-We6 ,ess5i< j int6 bool 7
return thisHiI.We R thisHjI.We84unc 5this B-We6 S)ap5i< j int6 7
thisHiI< thisHjI E thisHjI< thisHiI8
13.! as+es 8 Cryptograp+y
A hash "unction ta#es a set o" data and reduces it to a
smaller "ixed si>e 4ashes are "reBuently used in pro,
gramming "or everything "rom loo#ing up data to eas,
ily detecting changes 4ash "unctions in Go are bro#en
into t%o categories( cryptographic and non,crypto,
graphic
he non,cryptographic hash "unctions can be "ound
underneath the hash pac#age and include adler?$
crc?$ crc@and 4nv 4ereFs an example using crc?(
-
8/22/2019 go Language book
149/165
145 Te %ore Pa$+ages
pac&ae main
import 534mt33hash/crc?3
6
4unc main56 7h :E crc?.Ne);;;56
h.1rite5HIb-te53test366v :E h.Sum?564mt.+rintln5v6
8
he crc? hash obLect implements the 1riter inter,
"ace$ so %e can %rite bytes to it li#e any other 1riter
=nce %eFve %ritten everything %e %ant %e callSum?56to return a uint? A common use "or crc?is
to compare t%o "iles I" the Sum?value "or both "iles is
the same$ itFs highly li#ely @though not 100V certain
that the "iles are the same I" the values are di""erent
then the "iles are de"initely not the same(
-
8/22/2019 go Language book
150/165
Te %ore Pa$+ages 146
pac&ae main
import 534mt33hash/crc?33io/ioutil3
6
4unc et0ash54ilename strin6 5uint?< error6 7
bs< err :E ioutil.ead!ile53test$.txt36i4 err LE nil 7
return < err8h :E crc?.Ne);;;56h.1rite5bs6return h.Sum?56< nil
8
4unc main56 7h$< err :E et0ash53test$.txt36i4 err LE nil 7
return8h< err :E et0ash53test.txt36i4 err LE nil 7
return84mt.+rintln5h$< h< h$ EE h6
8
Cryptographic hash "unctions are similar to their non,
cryptographic counterparts$ but they have the added
property o" being hard to reverse Given the crypto,
graphic hash o" a set o" data$ itFs extremely di""icult to
-
8/22/2019 go Language book
151/165
147 Te %ore Pa$+ages
determine %hat made the hash hese hashes are o",
ten used in security applications
=ne common cryptographic hash "unction is #no%n as
&4A,1 4ereFs ho% it is used(
pac&ae main
import 534mt33cr-pto/sha$3
6
4unc main56 7h :E sha$.Ne)56h.1rite5HIb-te53test366
bs :E h.Sum5HIb-te7864mt.+rintln5bs6
8
his example is very similar to the crc?one$ because
both crc? and sha$ implement the hash.0ash inter,
"ace he main di""erence is that %hereas crc? com,putes a .2 bit hash$ sha$ computes a 180 bit hash
here is no native type to represent a 180 bit number$
so %e use a slice o" 20 bytes instead
13. Ser9ers
riting net%or# servers in Go is very easy e %ill
-
8/22/2019 go Language book
152/165
Te %ore Pa$+ages 148
"irst ta#e a loo# at ho% to create a CP server(
pac&ae main
import 53encodin/ob334mt33net3
6
4unc server56 7// listen on a portln< err :E net.,isten53tcp3< 3:AAAA36i4 err LE nil 7
4mt.+rintln5err6return
8
4or 7// accept a connectionc< err :E ln.Wccept56i4 err LE nil 7
4mt.+rintln5err6continue
8// handle the connectiono handleServerConnection5c6
88
-
8/22/2019 go Language book
153/165
149 Te %ore Pa$+ages
4unc handleServerConnection5c net.Conn6 7
// receive the messaevar ms strinerr :E ob.Ne)%ecoder5c6.%ecode5Jms6i4 err LE nil 7
4mt.+rintln5err68 else 7
4mt.+rintln53eceived3< ms68
c.Close568
4unc client56 7// connect to the serverc< err :E net.%ial53tcp3< 3$P...$:AAAA36i4 err LE nil 7
4mt.+rintln5err6
return8
// send the messaems :E 30ello 1orld34mt.+rintln53Sendin3< ms6err E ob.Ne);ncoder5c6.;ncode5ms6i4 err LE nil 7
4mt.+rintln5err68
c.Close568
-
8/22/2019 go Language book
154/165
Te %ore Pa$+ages 150
4unc main56 7
o server56o client56
var input strin4mt.Scanln5Jinput6
8
his example uses the encodin/ob pac#age %hichma#es it easy to encode Go values so that other Go
programs @or the same Go program in this case can
read them Additional encodings are available in pac#,
ages underneath encodin@li#e encodin/json as %ell
as in .rd party pac#ages @"or example %e could use
labix.or/v/mo/bson "or bson support
TTP
4P servers are even easier to setup and use(
-
8/22/2019 go Language book
155/165
151 Te %ore Pa$+ages
pac&ae main
import 53net/http3 Q 3io36
4unc hello5res http.esponse1riter< re[9http.e[uest6 7
res.0eader56.Set53Content#-pe3
Rtitle>0ello 1orldR/title>R/head>Rbod->
0ello 1orldLR/bod->
R/html>Gation in Go is through goroutines and channels as
discussed in chapter 10 4o%ever Go does provide
more traditional multithreading routines in the s-nc
and s-nc/atomicpac#ages
$ute-es
A mutex @mutal exclusive loc# loc#s a section o" code
to a single thread at a time and is used to protect
shared resources "rom non,atomic operations 4ere is
an example o" a mutex(
-
8/22/2019 go Language book
161/165
157 Te %ore Pa$+ages
pac&ae main
import 534mt33s-nc33time3
64unc main56 7
m :E ne)5s-nc.*utex6
4or i :E Q i R $Q i 7o 4unc5i int6 7
m.,oc&564mt.+rintln5i< 3start36time.Sleep5time.Second64mt.+rintln5i< 3end36m.Unloc&56
85i6
8
var input strin4mt.Scanln5Jinput6
8
hen the mutex @m is loc#ed any other attempt to loc#
it %ill bloc# until it is unloc#ed Great care should be
ta#en %hen using mutexes or the synchroni>ation
primitives provided in the s-nc/atomicpac#age
raditional multithreaded programming is di""icult
itFs easy to ma#e mista#es and those mista#es are
hard to "ind$ since they may depend on a very speci"ic$relatively rare$ and di""icult to reproduce set o" circum,
-
8/22/2019 go Language book
162/165
Te %ore Pa$+ages 158
stances =ne o" GoFs biggest strengths is that the con,
currency "eatures it provides are much easier to under,stand and use properly than threads and loc#s
-
8/22/2019 go Language book
163/165
14 ,e-t Steps
e no% have all the in"ormation %e need to %rite
most Go programs 'ut it %ould be dangerous to con,clude that there"ore %e are competent programmers
Programming is as much a cra"t as it is Lust having
#no%ledge his chapter %ill provide you %ith some
suggestions about ho% best to master the cra"t o" pro,
gramming
14.1 Study t+e $asters
Part o" becoming a good artist or %riter is studying the
%or#s o" the masters ItFs no di""erent %ith program,
ming =ne o" the best %ays to become a s#illed pro,
grammer is to study the source code produced by oth,
ers Go is %ell suited to this tas# since the source code
"or the entire proLect is "reely available
or example %e might ta#e a loo# at the source code to
the io/ioutillibrary available at(
http(
-
8/22/2019 go Language book
164/165
,e-t Steps 160
5ead the code slo%ly and deliberately ry to under,
stand every line and read the supplied comments orexample in the ead!ile method thereFs a comment
that says this(
// tOs a ood but not certain bet that !ilen4o// )ill tell us exactl- ho) much to read< so// letOs tr- it but be prepared 4or the ans)er
// to be )ron.
his method probably started out simpler than %hat it
became so this is a great example o" ho% programs can
evolve a"ter testing and %hy itFs important to supply
comments %ith those changes All o" the source code
"or all o" the pac#ages is available at(
http(
-
8/22/2019 go Language book
165/165
161 ,e-t Steps
14.3 Team >p
7ost real,%orld so"t%are proLects are done in teams$
there"ore learning ho% to %or# in a team is crucial I"
you can$ "ind a "riend E maybe a classmate E and team
up on a proLect earn ho% to divide a proLect into
pieces you can both %or# on simultaneously
Another option is to %or# on an open source proLect
ind a .rdparty library$ %rite some code @perhaps "ix a
bug$ and submit it to the maintainer Go has a gro%,
ing community %hich can be reached via the mailing
list @http(