IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors Eective Go
Jongseok Choi
Eective Go Jongseok Choi 1 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Outline
1
Introduction
Example
2
Formatting
3
Commentary
4
Names
Package names
Getters
Interface names
MixedCaps
5
Semicolons
6
Control structures
If
Reassignment
For
Switch
Type switch
7
Functions
Multiple return values
Named results
Defer
8
Data
Allocation with new
Constructors
Allocation with make
Arrays
Slices
Two-dimensional slices
Maps
Printing
Append
9
Initialization
Constants
Variables
init function
10
Method
Pointer vs. values
11
Interfaces and other types
Interfaces
Type assertions
Generality
12
The blank identier
Multiple assignment
Unused variables
Import for side eect
Interface checks
13
Embedding
14
Concurrency
Communicating
Goroutines
Channels
Channels of channels
15
Errors
Panic
Recover
16
A web server
Eective Go Jongseok Choi 2 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Outline
1
Introduction
Example
2
Formatting
3
Commentary
4
Names
Package names
Getters
Interface names
MixedCaps
5
Semicolons
6
Control structures
If
Reassignment
For
Switch
Type switch
7
Functions
Multiple return values
Named results
Defer
8
Data
Allocation with new
Constructors
Allocation with make
Arrays
Slices
Two-dimensional slices
Maps
Printing
Append
9
Initialization
Constants
Variables
init function
10
Method
Pointer vs. values
11
Interfaces and other types
Interfaces
Type assertions
Generality
12
The blank identier
Multiple assignment
Unused variables
Import for side eect
Interface checks
13
Embedding
14
Concurrency
Communicating
Goroutines
Channels
Channels of channels
15
Errors
Panic
Recover
16
A web server
Eective Go Jongseok Choi 3 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Introduction
What is Go?
Although it borrows ideas from existing languages, it has unusual properties that
make eective Go programs dierent in character from programs written in its
relatives.
A straightforward translation
produce a satisfactory result.
In other words, to write Go well, it's
idioms.
Eective Go Jongseok Choi 4 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Example
Example
The Go package sources
1
are intended to serve not only as the core library but also as
examples of how to use the language.
1
https://golang.org/src/Eective Go Jongseok Choi 5 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Outline
1
Introduction
Example
2
Formatting
3
Commentary
4
Names
Package names
Getters
Interface names
MixedCaps
5
Semicolons
6
Control structures
If
Reassignment
For
Switch
Type switch
7
Functions
Multiple return values
Named results
Defer
8
Data
Allocation with new
Constructors
Allocation with make
Arrays
Slices
Two-dimensional slices
Maps
Printing
Append
9
Initialization
Constants
Variables
init function
10
Method
Pointer vs. values
11
Interfaces and other types
Interfaces
Type assertions
Generality
12
The blank identier
Multiple assignment
Unused variables
Import for side eect
Interface checks
13
Embedding
14
Concurrency
Communicating
Goroutines
Channels
Channels of channels
15
Errors
Panic
Recover
16
A web server
Eective Go Jongseok Choi 6 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Formatting
Formatting issues are the most contentious but the least consequential.
With Go we take an unusual approach and let the machine take care of most
formatting issues.
Thegofmtreads a Go program and emits the source in a standard style
indentation and vertical alignment, retaining and if necessary reformatting
comments.
1t y p e
2 n a m e / /
3 v a l u e / /
4}
Code 1:
1t y p e
2 n a m e / /
3 v a l u e / /
4}
Code 2:
Eective Go Jongseok Choi 7 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Formatting
Indentation
We use tabs for indentation and gofmt emits them by default. Use spaces only if you
must.
Line length
Go has no line length limit. Don't worry about overowing a punched card. If a line
feels too long, wrap it and indent with an extra tab.
Parentheses
Go needs fewer parentheses than C and Java: control structures (if, for, switch) do not
have parentheses in their syntax. Also, the operator precedence hierarchy is shorter and
clearer, so
1x
Code 3:
Eective Go Jongseok Choi 8 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Outline
1
Introduction
Example
2
Formatting
3
Commentary
4
Names
Package names
Getters
Interface names
MixedCaps
5
Semicolons
6
Control structures
If
Reassignment
For
Switch
Type switch
7
Functions
Multiple return values
Named results
Defer
8
Data
Allocation with new
Constructors
Allocation with make
Arrays
Slices
Two-dimensional slices
Maps
Printing
Append
9
Initialization
Constants
Variables
init function
10
Method
Pointer vs. values
11
Interfaces and other types
Interfaces
Type assertions
Generality
12
The blank identier
Multiple assignment
Unused variables
Import for side eect
Interface checks
13
Embedding
14
Concurrency
Communicating
Goroutines
Channels
Channels of channels
15
Errors
Panic
Recover
16
A web server
Eective Go Jongseok Choi 9 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Commentary
Comments style
C-style /* */ block
C++-style // line
The programgodocprocesses Go source les to extract documentation about the con-
tents of the package.
For multi-le packages, the package comment only needs to be present in one
le, and any one will do.
1/ *
2P a c k a g e
3
4T h e
5
6 r e g e x p
7 c o n c a t e n a t i o n
8 c o n c a t e n a t i o n
9 {
10 c l o s u r e
11 t e r m
12 t e r m
13 '^ '
14 '$'
15 '. '
16 c h a r a c t e r
17 '[ '
18 '( '
19* /
20p a c k a g e
Eective Go Jongseok Choi 10 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Commentary
If the package is simple, the package comment can be brief.
Depending on the context, godoc might not even reformat comments, so make
sure they look good straight up.
Inside a package, any comment immediately preceding a top-level declaration
serves as a doc comment for that declaration.
The rst sentence should be a one-sentence summary that starts with the name
being declared.
1/ /
2/ /
1/ /
2/ /
3f u n c
Eective Go Jongseok Choi 11 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Commentary
Imagine you couldn't remember the name \Compile" but were looking for the parsing
function for regular expressions.
If all the doc comments in the package began, "This function...", grep wouldn't
help you remember the name.
1$
2C o m p i l e
p a r s e d
c a n n o t
Eective Go Jongseok Choi 12 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Commentary
Go's declaration syntax allows grouping of declarations.
A single doc comment can introduce a group of related constants or variables.
Grouping can also indicate relationships between items, such as the fact that a
set of variables is protected by a mutex.
1/ /
2v a r
3 E r r I n t e r n a l
4 E r r U n m a t c h e d L p a r
5 E r r U n m a t c h e d R p a r
6 . . .
7)
1i m p o r t
2
3v a r
4 c o u n t L o c k
5 i n p u t C o u n t
6 o u t p u t C o u n t
7 e r r o r C o u n t
8)
Eective Go Jongseok Choi 13 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Outline
1
Introduction
Example
2
Formatting
3
Commentary
4
Names
Package names
Getters
Interface names
MixedCaps
5
Semicolons
6
Control structures
If
Reassignment
For
Switch
Type switch
7
Functions
Multiple return values
Named results
Defer
8
Data
Allocation with new
Constructors
Allocation with make
Arrays
Slices
Two-dimensional slices
Maps
Printing
Append
9
Initialization
Constants
Variables
init function
10
Method
Pointer vs. values
11
Interfaces and other types
Interfaces
Type assertions
Generality
12
The blank identier
Multiple assignment
Unused variables
Import for side eect
Interface checks
13
Embedding
14
Concurrency
Communicating
Goroutines
Channels
Channels of channels
15
Errors
Panic
Recover
16
A web server
Eective Go Jongseok Choi 14 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Package names
Package names
When a package is imported, the package name becomes an accessor for the contents.
By convention, packages are given
there should be no need for underscores or mixedCaps.
Another convention is that the package name is
directory.
the package in src/encoding/base64 is imported as "encoding/base64" but has name
base64.
1i m p o r t
Use the package structure to help you choose good names.
Another short example is once.Do.
once.Do(setup) reads well and would not be improved by writing
once.DoOrWaitUntilDone(setup)
Long names don't automatically make things more readable.
A helpful doc comment can often be more valuable than an extra long name.
Eective Go Jongseok Choi 15 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Getters
Getters
Go doesn't provide automatic support for getters and setters.
There's nothing wrong with providing getters and setters yourself.
But it's neither idiomatic nor necessary to put Get into the getter's name.
If you have a eld called owner (lower case, unexported).
The getter method should be called Owner (upper case, exported), not GetOwner.
A setter function, if needed, will likely be called SetOwner.
1o w n e r
2if
3 o b j
4}
Eective Go Jongseok Choi 16 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Interface names
Interface names
By convention, one-method interfaces are named by the method name plus an -er
sux or similar modication to construct an agent noun
Reader, Writer, Formatter, CloseNotier etc.
There are a number of such names and it is productive to honor them and the function
names they capture.
To avoid confusion, do not give your method one of those names unless it has the
same signature and meaning.
If your type implements a method with the same meaning as a method on a
well-known type.
Give it the same name and signature call your string-converter method String not
ToString.
Eective Go Jongseok Choi 17 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
MixedCaps
MixedCaps
Finally, the convention in Go is to use MixedCaps or mixedCaps rather than
underscores to write multiword names.
Eective Go Jongseok Choi 18 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Outline
1
Introduction
Example
2
Formatting
3
Commentary
4
Names
Package names
Getters
Interface names
MixedCaps
5
Semicolons
6
Control structures
If
Reassignment
For
Switch
Type switch
7
Functions
Multiple return values
Named results
Defer
8
Data
Allocation with new
Constructors
Allocation with make
Arrays
Slices
Two-dimensional slices
Maps
Printing
Append
9
Initialization
Constants
Variables
init function
10
Method
Pointer vs. values
11
Interfaces and other types
Interfaces
Type assertions
Generality
12
The blank identier
Multiple assignment
Unused variables
Import for side eect
Interface checks
13
Embedding
14
Concurrency
Communicating
Goroutines
Channels
Channels of channels
15
Errors
Panic
Recover
16
A web server
Eective Go Jongseok Choi 19 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Semicolons
Like C, Go's formal grammar uses semicolons to terminate statements
But unlike in C, those semicolons do not appear in the source.
Instead the lexer uses a simple rule to insert semicolons automatically as it scans,
so the input text is mostly free of them.
Semicolons insertion rules
if the newline comes after a token that could end a statement, insert a semicolon.
1b r e a k
A semicolon can also
statement for
1go
Eective Go Jongseok Choi 20 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Semicolons
One consequence of the semicolon insertion rules is that you
brace
1if
2 g
3}
1if / /
2{ / /
3 g
4}
Eective Go Jongseok Choi 21 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Outline
1
Introduction
Example
2
Formatting
3
Commentary
4
Names
Package names
Getters
Interface names
MixedCaps
5
Semicolons
6
Control structures
If
Reassignment
For
Switch
Type switch
7
Functions
Multiple return values
Named results
Defer
8
Data
Allocation with new
Constructors
Allocation with make
Arrays
Slices
Two-dimensional slices
Maps
Printing
Append
9
Initialization
Constants
Variables
init function
10
Method
Pointer vs. values
11
Interfaces and other types
Interfaces
Type assertions
Generality
12
The blank identier
Multiple assignment
Unused variables
Import for side eect
Interface checks
13
Embedding
14
Concurrency
Communicating
Goroutines
Channels
Channels of channels
15
Errors
Panic
Recover
16
A web server
Eective Go Jongseok Choi 22 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Control structures
The control structures of Go are related to those of C but dier in important ways.
There is nodoorwhileloop, only a slightly generalizedfor.
ifandswitchaccept an optional initialization statement for/
breakandcontinuestatements take
or continue.
there are new control structures including
communications multiplexer,select.
There are no parentheses and the bodies must always be brace-delimited.
Eective Go Jongseok Choi 23 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
If
If
In Go,
Mandatory braces.
ifandswitchaccept an initialization statement.
The unnecessaryelseis omitted.
1if
2 r e t u r n
3}
1if
2 l o g
3 r e t u r n
4}
Eective Go Jongseok Choi 24 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Reassignment
Redeclaration and reassignment
In a := declaration a variable v may appear even if it has already been declared,
provided:
This declaration is in the same scope as the existing declaration of v (if v is
already declared in an outer scope, the declaration will create a new variablex)
The corresponding value in the initialization is assignable to v.
There is at least one other variable in the declaration that is being declared anew.
1f
2d
Eective Go Jongseok Choi 25 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
For
For
The Goforloop is similar to|but not the same as|C's.
It uniesforandwhileand there is do-while.
There are three forms, only one of which has semicolons.
1/ /
2f o r
3}
4
5/ /
6f o r
7}
8
9/ /
10f o r
11}
Eective Go Jongseok Choi 26 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
For
For
If you're looping over an array, slice, string, or map, or reading from a channel, a range
clause can manage the loop.
If you only need the rst item in the range (the key or index), drop the second:\
key := range m."
If you only need the second item in the range (the value), use the blank identier,
an underscore, to discard the rst: \,value := range m"
1f o r
2 n e w M a p
3}
Eective Go Jongseok Choi 27 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
For
For
Finally,
Go has no comma operator and ++ and { are statements not expressions.
if you want to run multiple variables in a for you should use parallel assignment.
1/ /
2f o r
3 a
4}
Eective Go Jongseok Choi 28 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Switch
Switch
Go'sswitchis more general than C's.
The expressions need not be constants or even integers.
The cases are evaluated top to bottom until a match is found.
If theswitchhas no expression it switches ontrue.
It's therefore possible to write anif-else-if-elsechain as aswitch.
1f u n c
2 s w i t c h
3 c a s e
4 r e t u r n
5 c a s e
6 r e t u r n
7 c a s e
8 r e t u r n
9 }
10 r e t u r n
11}
Eective Go Jongseok Choi 29 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Switch
Switch
There is no automatic fall through, but cases can be presented in comma-separated
lists.
1f u n c
2 s w i t c h
3 c a s e
4 r e t u r n
5 }
6 r e t u r n
7}
Eective Go Jongseok Choi 30 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Switch
Switch
Loop escape
Go that can be accomplished by putting a label on the loop and reaking" to
that label.
Thecontinuestatement also accepts an optional label but it applies only to
loops.
1L o o p
2 f o r
3 s w i t c h
4 c a s e
5 if
6 b r e a k
7 }
8 s i z e
9 u p d a t e
10
11 c a s e
12 if
13 e r r
14 b r e a k
15 }
16 if
17 b r e a k
18 }
19 s i z e
20 u p d a t e
21 }
22 }
1/ /
2/ /
3/ /
4f u n c
5 f o r
6 s w i t c h
7 c a s e
8 r e t u r n
9 c a s e
10 r e t u r n
11 }
12 }
13 s w i t c h
14 c a s e
15 r e t u r n
16 c a s e
17 r e t u r n
18 }
19 r e t u r n
20}
Code 4: switch
Eective Go Jongseok Choi 31 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Type switch
Type switch
A switch can also be used to discover the dynamic type of an interface variable.
Such a type switch uses the syntax of type
inside the parentheses.
1v a r
2t
3s w i t c h
4d e f a u l t
5 f m t / /
h a s
6c a s e
7 f m t / /
8c a s e
9 f m t / /
10c a s e
11 f m t / /
12c a s e
13 f m t / /
14}
Eective Go Jongseok Choi 32 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Outline
1
Introduction
Example
2
Formatting
3
Commentary
4
Names
Package names
Getters
Interface names
MixedCaps
5
Semicolons
6
Control structures
If
Reassignment
For
Switch
Type switch
7
Functions
Multiple return values
Named results
Defer
8
Data
Allocation with new
Constructors
Allocation with make
Arrays
Slices
Two-dimensional slices
Maps
Printing
Append
9
Initialization
Constants
Variables
init function
10
Method
Pointer vs. values
11
Interfaces and other types
Interfaces
Type assertions
Generality
12
The blank identier
Multiple assignment
Unused variables
Import for side eect
Interface checks
13
Embedding
14
Concurrency
Communicating
Goroutines
Channels
Channels of channels
15
Errors
Panic
Recover
16
A web server
Eective Go Jongseok Choi 33 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Multiple return values
Multiple return values
One of Go's unusual features is that functions and methods can return multiple
values.
This form can be used to improve on a couple of clumsy idioms in C programs.
in-band error returns such as -1 for EOF and modifying an argument passed by address.
1f u n c
1f u n c
2 f o r
3 }
4 x
5 f o r
6 x
7 }
8 r e t u r n
9}
Eective Go Jongseok Choi 34 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Named results
Named result parameters
The return or result \parameters" of a Go function can be given names and used as
regular variables, just like the incoming parameters.
When named, they are initialized to the zero values for their types when the
function begins.
1f u n c
2 f o r
3 v a r
4 nr
5 n
6 b u f
7 }
8 r e t u r n
9}
Eective Go Jongseok Choi 35 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Defer
Defer
Go's defer statement schedules a function call (the deferred function) to be run
immediately before the function executing the defer returns.
It's an unusual but eective way to deal with situations such as resources that
must be released regardless of which path a function takes to return.
Deferring a call to a function such as Close has two advantages.
First, it guarantees that you will never forget to close the le.
Second, it means that the close sits near the open.
1/ /
2f u n c
3 f
4 if
5 r e t u r n
6 }
7 d e f e r / /
8
9 v a r
10 b u f
11 f o r
12 n
13 r e s u l t / /
14 if
15 if
16 b r e a k
17 }
18 r e t u r n / /
19 }
20 }
21 r e t u r n / /
22}
Eective Go Jongseok Choi 36 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Defer
Defer
The arguments to the deferred function are evaluated when the defer executes, not
when the call executes.
Deferred functions are executed in LIFO order.
1f o r
2 d e f e r
3}
A more plausible example is a simple way to trace function execution through the
program.
1f u n c
2f u n c
3
4/ /
5f u n c
6 t r a c e
7 d e f e r
8 / /
9}
Eective Go Jongseok Choi 37 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Defer
Defer
We can do better by exploiting the fact that arguments to deferred functions are
evaluated when the defer executes.
1f u n c
2 f m t
3 r e t u r n
4}
5
6f u n c
7 f m t
8}
9
10f u n c
11 d e f e r
12 f m t
13}
14
15f u n c
16 d e f e r
17 f m t
18 a
19}
20
21f u n c
22 b
23}
Result
e n t e r i n g : b
i n b
e n t e r i n g : a
i n a
l e a v i n g : a
l e a v i n g : b
Eective Go Jongseok Choi 38 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Outline
1
Introduction
Example
2
Formatting
3
Commentary
4
Names
Package names
Getters
Interface names
MixedCaps
5
Semicolons
6
Control structures
If
Reassignment
For
Switch
Type switch
7
Functions
Multiple return values
Named results
Defer
8
Data
Allocation with new
Constructors
Allocation with make
Arrays
Slices
Two-dimensional slices
Maps
Printing
Append
9
Initialization
Constants
Variables
init function
10
Method
Pointer vs. values
11
Interfaces and other types
Interfaces
Type assertions
Generality
12
The blank identier
Multiple assignment
Unused variables
Import for side eect
Interface checks
13
Embedding
14
Concurrency
Communicating
Goroutines
Channels
Channels of channels
15
Errors
Panic
Recover
16
A web server
Eective Go Jongseok Choi 39 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Allocation with new
Allocation with new
Go has two allocation primitives, the built-in functionsnewandmake.
new(T) allocates zeroed storage for a new item of type T and returns its address,
a value of type *T.
1p / /
2v a r / /
Eective Go Jongseok Choi 40 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Constructors
Constructors and composite literals
Sometimes the zero value isn't good enough and an initializing constructor is
necessary.
Using new(T), there is a lot of boiler plate.
We can simplify it using a composite literal, which is an expression that creates a
new instance each time it is evaluated.
Note that, unlike in C, it's perfectly OK to return the address of a local variable.
The storage associated with the variable survives after the function returns.
1f u n c
2 if
3 r e t u r n
4 }
5 f
6 r e t u r n
7}
In fact, taking the address of a composite literal allocates a fresh instance each time it
is evaluated, so we can combine these last two lines.
1r e t u r n
Eective Go Jongseok Choi 41 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Constructors
Composite literals
Composite literals can also be created for arrays, slices, and maps, with the eld labels
being indices or map keys as appropriate.
1a
2s
3m
Eective Go Jongseok Choi 42 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Allocation with make
Allocation with make
The built-in function make(T, args) serves a purpose dierent from new(T).
It.
It returns an initialized (not zeroed) value of type T (not *T).
1v a r / /
2v a r / /
3
4/ /
5v a r
6* / /
7
8/ /
9v
Eective Go Jongseok Choi 43 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Arrays
Arrays
Arrays are useful when planning the detailed layout of memory.
They are a building block for slices.
Major dierences between the ways arrays work in Go and C:
Arrays are values. Assigning one array to another copies all the elements.
If you pass an array to a function, it will receive a copy of the array,
to it.
The size of an array is part of its type. The types [10]int and [20]int are distinct.
1v a r / /
2v a r / /
3
4/ /
5v a r
6* / /
7
8/ /
9v
Eective Go Jongseok Choi 44 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Slices
Slices
Slices wrap arrays to give a more general, powerful, and convenient interface to
sequences of data.
Most array programming in Go is done with slices rather than simple arrays.
Except for items with explicit dimension such as transformation matrices.
Slices hold references to an underlying array,
If you assign one slice to another, both refer to the same array.
If a function takes a slice argument, changes it makes to the elements of the slice will
be visible to the caller.
1f u n c
2 l
3 if / /
4 / /
5 n e w S l i c e
6 / /
7 c o p y
8 s l i c e
9 }
10 s l i c e
11 f o r
12 s l i c e
13 }
14 r e t u r n
15}
Eective Go Jongseok Choi 45 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Two-dimensional slices
Two-dimensional slices
Go's arrays and slices are one-dimensional.
To create the equivalent of a 2D array or slice, it is necessary to dene an
array-of-arrays or slice-of-slices.
1t y p e / /
2t y p e / /
Because slices are variable-length, it is possible to have each inner slice be a
dierent length.
1t e x t
2 []
3 []
4 []
5}
Eective Go Jongseok Choi 46 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Two-dimensional slices
Two-dimensional slices
Sometimes it's necessary to allocate a 2D slice, a situation that can arise when
processing scan lines of pixels, for instance.
One is to allocate each slice independently.
1/ /
2p i c t u r e / /
3/ /
4f o r
5 p i c t u r e
6}
And now as one allocation, sliced into lines:
1/ /
2p i c t u r e / /
3/ /
4p i x e l s / /
p i c t u r e
5/ /
p i x e l s
6f o r
7 p i c t u r e
8}
Eective Go Jongseok Choi 47 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Maps
Maps
Maps are a convenient and powerful built-in data structure that associate values of
one type (the key) with values of another type (the element or value).
The key can be of any type for which the equality operator is dened.
Slices cannot be used as map keys, because equality is not dened on them.
Maps can be constructed using the usual composite literal syntax with
colon-separated key-value pairs
1a t t e n d e d
2 "
3 "
4 . . .
5}
6
7if / /
8 f m t
9}
To delete a map entry, use the delete built-in function, whose arguments are the
map and the key to be deleted.
1d e l e t e / /
Eective Go Jongseok Choi 48 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Printing
Printing
Formatted printing in Go uses a style similar to C's printf family but is richer and more
general.
For each ofPrintf,FprintfandSprintfthere is another pair of functions, for
instancePrintandPrintln.
1f m t
2f m t
3f m t
4f m t
The numeric formats such as %d do not take ags for signedness or size.
1v a r
2f m t
18446744073709551615 ; -1 -1
If you just want the default conversion, such as decimal for integers, you can use
the catchall format %v (for \value")
1f m t / /
Eective Go Jongseok Choi 49 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Printing
Printing
When printing a struct, the modied format %+v annotates the elds of the structure
with their names, and for any value the alternate format %#v prints the value in full
Go syntax.
1t y p e
2 a
3 b
4 c
5}
6t
7f m t
8f m t
9f m t
10f m t
1& { 7 - 2 . 3 5
2&{
3&
4m a p
: - 2 5 2 0 0 }
Code 5:
Eective Go Jongseok Choi 50 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Printing
Printing
Another handy format is %T, which prints the type of a value.
1f m t
If you want to control the default format for a custom type, all that's required is
to dene a method with the signature String() string on the type.
1f u n c
2 r e t u r n
3}
4f m t
Our String method is able to call Sprintf because the print routines are fully
reentrant.
1t y p e
2f u n c
3 r e t u r n / /
.
4}
Eective Go Jongseok Choi 51 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Append
Append
The signature of append is dierent from our custom Append function above.
Where T is a placeholder for any given type.
You can't actually write a function in Go where the type T is determined by the
caller.
That's whyappendis built in: it needs support from the compiler.
1f u n c
The result needs to be returned because, as with our hand-written Append, the under-
lying array may change.
But what if we wanted to do what our Append does and append a slice to a slice?
1x
2y
3x
4f m t
Eective Go Jongseok Choi 52 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Outline
1
Introduction
Example
2
Formatting
3
Commentary
4
Names
Package names
Getters
Interface names
MixedCaps
5
Semicolons
6
Control structures
If
Reassignment
For
Switch
Type switch
7
Functions
Multiple return values
Named results
Defer
8
Data
Allocation with new
Constructors
Allocation with make
Arrays
Slices
Two-dimensional slices
Maps
Printing
Append
9
Initialization
Constants
Variables
init function
10
Method
Pointer vs. values
11
Interfaces and other types
Interfaces
Type assertions
Generality
12
The blank identier
Multiple assignment
Unused variables
Import for side eect
Interface checks
13
Embedding
14
Concurrency
Communicating
Goroutines
Channels
Channels of channels
15
Errors
Panic
Recover
16
A web server
Eective Go Jongseok Choi 53 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Initialization
Complex structures can be built during initialization and the ordering issues among
initialized objects, even among dierent packages, are handled correctly.
Eective Go Jongseok Choi 54 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Constants
Constants
They are created at compile time, even when dened as locals in functions, and can
only be numbers, characters (runes), strings or booleans.
For instance, 1<<3 is a constant expression, whilemath.Sin(math.Pi/4)is not
because the function call to math.Sin needs to happen at run time.
expressions can be implicitly repeated.
1t y p e
2
3c o n s t
4 _
5 KB
6 MB
7 GB
8 TB
9 PB
10 EB
11 ZB
12 YB
13)
1f u n c
2 s w i t c h
3 c a s e
4 r e t u r n
5 c a s e
6 r e t u r n
7 c a s e
8 r e t u r n
9 c a s e
10 r e t u r n
11 c a s e
12 r e t u r n
13 c a s e
14 r e t u r n
15 c a s e
16 r e t u r n
17 c a s e
18 r e t u r n
19 }
20 r e t u r n
21}
Eective Go Jongseok Choi 55 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Variables
Variables
Variables can be initialized just like constants but the initializer can be a general
expression computed at run time.
1i m p o r t
2
3v a r
4 h o m e
5 u s e r
6 g o p a t h
7)
Eective Go Jongseok Choi 56 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
init function
initfunction
Finally each source le can dene its own niladicinitfunction to set up whatever
state is required.
Actually each le can have multipleinitfunctions.
Finally means nally:initis called after all the variable declarations in the
package have evaluated their initializers.
Those are evaluated only after all the imported packages have been initialized.
A common use ofinitfunctions is to verify or repair correctness of the program
state before real execution begins.
1f u n c
2 if
3 l o g
4 }
5 if
6 h o m e
7 }
8 if
9 g o p a t h
10 }
11 / /
12 f l a g
13}
Eective Go Jongseok Choi 57 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Outline
1
Introduction
Example
2
Formatting
3
Commentary
4
Names
Package names
Getters
Interface names
MixedCaps
5
Semicolons
6
Control structures
If
Reassignment
For
Switch
Type switch
7
Functions
Multiple return values
Named results
Defer
8
Data
Allocation with new
Constructors
Allocation with make
Arrays
Slices
Two-dimensional slices
Maps
Printing
Append
9
Initialization
Constants
Variables
init function
10
Method
Pointer vs. values
11
Interfaces and other types
Interfaces
Type assertions
Generality
12
The blank identier
Multiple assignment
Unused variables
Import for side eect
Interface checks
13
Embedding
14
Concurrency
Communicating
Goroutines
Channels
Channels of channels
15
Errors
Panic
Recover
16
A web server
Eective Go Jongseok Choi 58 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Pointer vs. values
Pointer vs. values
In the discussion of slices above, we wrote an Append function. We can dene it as a
method on slices instead.
Value and pointer approach:
1t y p e
2
3f u n c
4 / /
d e f i n e d
5}
1f u n c
2 s l i c e
3 / /
4 *
5}
Better denition like a standardWritemethod.
1f u n c
2 s l i c e
3 / /
4 *
5 r e t u r n
6}
When the value is addressable, the language takes care of the common case of in-
voking a pointer method on a value by inserting the address operator.
1v a r
2f m t
Eective Go Jongseok Choi 59 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Pointer vs. values
Pointer vs. values
Quiz : What is the value ofc[11]?
1p a c k a g e
2
3i m p o r t
4 "
5)
6
7t y p e
8
9f u n c
10 v
11 v
12 v
13 c
14 d
15 q
16
17 f m t
18}
The rule about pointers vs. values for receivers is that value methods can be invoked
on pointers and values, but pointer methods can only be invoked on pointers.
Eective Go Jongseok Choi 60 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Outline
1
Introduction
Example
2
Formatting
3
Commentary
4
Names
Package names
Getters
Interface names
MixedCaps
5
Semicolons
6
Control structures
If
Reassignment
For
Switch
Type switch
7
Functions
Multiple return values
Named results
Defer
8
Data
Allocation with new
Constructors
Allocation with make
Arrays
Slices
Two-dimensional slices
Maps
Printing
Append
9
Initialization
Constants
Variables
init function
10
Method
Pointer vs. values
11
Interfaces and other types
Interfaces
Type assertions
Generality
12
The blank identier
Multiple assignment
Unused variables
Import for side eect
Interface checks
13
Embedding
14
Concurrency
Communicating
Goroutines
Channels
Channels of channels
15
Errors
Panic
Recover
16
A web server
Eective Go Jongseok Choi 61 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Interfaces
Interfaces
Interfaces in Go provide a way to specify the behavior of an object
A type can implement multiple interfaces
A collection can be sorted by the routines in packagesortif it implements
sort.Interface, which containsLen,Lessi;jintbool, andSwapi;jint
1t y p e
2
3/ /
4f u n c
5 r e t u r n
6}
7f u n c
8 r e t u r n
9}
10f u n c
11 s
12}
13
14/ /
15f u n c
16 s o r t
17 s t r
18 f o r
19 if
20 s t r
21 }
22 s t r
23 }
24 r e t u r n
25}
Eective Go Jongseok Choi 62 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Type assertions
Type assertions
Type switches are a form of conversion
They take an interface and, for each case in the switch, in a sense convert it to
the type of that case.
What if there's only one type we care about?
A one-case type switch would do, but so would.
1t y p e
2 S t r i n g
3}
4
5v a r / /
6s w i t c h
7c a s e
8 r e t u r n
9c a s e
10 r e t u r n
11}
12
13/ /
14str
15if
16 f m t
17}
18 f m t
19}
Eective Go Jongseok Choi 63 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Generality
Generality
Exporting just the interface makes it clear the value has no interesting behavior
beyond what is described in the interface.
It also avoids the need to repeat the documentation on every instance of a
common method.
1t y p e
2 B l o c k S i z e
3 E n c r y p t
4 D e c r y p t
5}
6
7t y p e
8 X O R K e y S t r e a m
9}
Eective Go Jongseok Choi 64 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Outline
1
Introduction
Example
2
Formatting
3
Commentary
4
Names
Package names
Getters
Interface names
MixedCaps
5
Semicolons
6
Control structures
If
Reassignment
For
Switch
Type switch
7
Functions
Multiple return values
Named results
Defer
8
Data
Allocation with new
Constructors
Allocation with make
Arrays
Slices
Two-dimensional slices
Maps
Printing
Append
9
Initialization
Constants
Variables
init function
10
Method
Pointer vs. values
11
Interfaces and other types
Interfaces
Type assertions
Generality
12
The blank identier
Multiple assignment
Unused variables
Import for side eect
Interface checks
13
Embedding
14
Concurrency
Communicating
Goroutines
Channels
Channels of channels
15
Errors
Panic
Recover
16
A web server
Eective Go Jongseok Choi 65 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Multiple assignment
The blank identier in multiple assignment
If an assignment requires multiple values on the left side, but one of the values will
not be used by the program, a blank identier on the left-hand-side of the assignment
avoids the need to create a dummy variable
discarded.
For instance, when calling a function that returns a value and an error, but only
the error is important, use the blank identier to discard the irrelevant value.
Occasionally you'll see code that discards the error value in order to ignore the
error.
This is.
1/ /
2fi
3if
4 f m t
Eective Go Jongseok Choi 66 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Unused variables
Unused imports and variables
It is an error to import a package or to declare a variable without using it.
When a program is, however, unused imports and
variables often arise.
It can be annoying, only to
have them be.
1p a c k a g e
2
3i m p o r t
4 " / /
5 " / /
6 "
7 "
8)
9
10f u n c
11 fd/ * ,
12 if
13 l o g
14 }
15 / /
16}
Eective Go Jongseok Choi 67 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Unused variables
Unused imports and variables
To silence complaints about the unused imports, use a blank identier to refer to a
symbol from the imported package.
Assigning the unused variablefdto the blank identier.
By convention, the global declarations to silence import errors should come right
after the imports and be commented.
Make them easy to nd.
As a reminder to clean things up later.
1p a c k a g e
2
3i m p o r t
4 "
5 "
6 "
7 "
8)
9
10v a r / /
11v a r / /
12
13f u n c
14 fd
15 if
16 l o g
17 }
18 / /
19 _
20}
Eective Go Jongseok Choi 68 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Import for side eect
Import for side eect
Sometimes it is useful to import a package only for its side eects, without any
explicit use.
For example, during itsinitfunction, thenet/http/pprofpackage registers
HTTP handlers that provide debugging information. It has an exported API, but
most clients need only the handler registration and access the data through a web
page.
This form of import makes clear that the package is being imported for its side
eects.
It doesn't have a name.
1i m p o r t
Eective Go Jongseok Choi 69 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Interface checks
Interface checks
A type need not declare explicitly that it implements an interface.
Instead, a type implements the interface just
methods.
In practice, most interface conversions are static and therefore checked at compile time.
Some interface checks do happen at run-time, though.
One instance is in theencoding/jsonpackage, which denes aMarshalerinterface.
If it's necessary only to ask whether a type implements an interface:
1if
2 f m t
3}
Eective Go Jongseok Choi 70 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Interface checks
Interface checks
There are no static conversions that would cause the compiler to verify this
automatically.
The type inadvertently fails to satisfy the interface.
The JSON encoder will still work, but will not use the custom implementation.
To guarantee that the implementation is correct, a global declaration using the
blank identier can be used in the package:
Involving a conversion of a*RawMessageto aMarshalerrequires that*RawMessage
implementsMarshaler, and that property will be.
1v a r
By convention, such declarations are only used when there are no static conversions
already present in the code, which is a rare event.
Eective Go Jongseok Choi 71 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Outline
1
Introduction
Example
2
Formatting
3
Commentary
4
Names
Package names
Getters
Interface names
MixedCaps
5
Semicolons
6
Control structures
If
Reassignment
For
Switch
Type switch
7
Functions
Multiple return values
Named results
Defer
8
Data
Allocation with new
Constructors
Allocation with make
Arrays
Slices
Two-dimensional slices
Maps
Printing
Append
9
Initialization
Constants
Variables
init function
10
Method
Pointer vs. values
11
Interfaces and other types
Interfaces
Type assertions
Generality
12
The blank identier
Multiple assignment
Unused variables
Import for side eect
Interface checks
13
Embedding
14
Concurrency
Communicating
Goroutines
Channels
Channels of channels
15
Errors
Panic
Recover
16
A web server
Eective Go Jongseok Choi 72 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Interface embedding
Go does not provide the typical, type-driven notion of subclassing, but it does have
the ability to orrow" pieces of an implementation by embedding types within a
struct or interface.
We've mentioned the io.Reader and io.Writer interfaces before; here are their
denitions.
1t y p e
2 R e a d
3}
4
5t y p e
6 W r i t e
7}
Embedding the two interfaces to form the new one
Only interfaces can be embedded within interfaces.
1/ /
i n t e r f a c e s
2t y p e
3 R e a d e r
4 W r i t e r
5}
Eective Go Jongseok Choi 73 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Struct embedding
The same basic idea applies to structs, but with more far-reaching implications.
It lists the types within the struct but does not give them eld names.
1/ /
2/ /
3t y p e
4 * / /
5 * / /
6}
The embedded elements are pointers to structs and of course must be initialized
to point to valid structs before they can be used.
1t y p e
2 r e a d e r
3 w r i t e r
4}
5
6f u n c
7 r e t u r n
8}
Eective Go Jongseok Choi 74 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Struct embedding
There's an important way in which embedding diers from subclassing.
When we embed a type, the methods of that type
type.
But when they are invoked, not the outer
one.
In our example, when the Read method of abufio.ReadWriteris invoked, it has
exactly the same eect as the forwarding method written out.
The receiver is the reader eld of theReadWriter, not theReadWriteritself.
Eective Go Jongseok Choi 75 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Struct embedding
1p a c k a g e
2
3i m p o r t
4 "
5 "
6 "
7)
8
9t y p e
10 C o m m a n d
11 *
12}
13
14f u n c
15 r e t u r n
16}
17f u n c
18 j o b
19}
20f u n c
21 / /
22 j o b
23 j o b
24}
This example shows an embedded eld
alongside a regular, named eld.
TheJobtype now has theLog,Logf
and other methods of*log.Logger.
TheLoggeris a regular eld of the
Jobstruct, so we can initialize it in
the usual way inside the constructor
forJob.
Embedding types introduces
are simple.
First, a eld or method X
the type.
Second, if the same name appears.
However, if the duplicate name is never mentioned in the program outside the type
denition, it is OK.
Eective Go Jongseok Choi 76 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Diversity
1p a c k a g e
2
3i m p o r t
4 "
5 "
6 "
7 "
8 "
9)
10
11t y p e
12 S t r
13 *
14 *
15}
16
17f u n c
18 r e t u r n
19 W r i t e r
20}
21
22f u n c
23 a
24 r e t u r n
25}
26
27f u n c
28 r e t u r n
29}
30
31f u n c
32 x
33 x
34
35 f m t
36
37 x
38 b
39 n
40 f m t
41
42 x
43
44 f m t
45}
Code 6:
1p a c k a g e
2
3i m p o r t
4 "
5 "
6 "
7 "
8 "
9)
10
11t y p e
12 S t r
13 *
14 w r i t e r
15}
16
17f u n c
18 r e t u r n
19 w r i t e r
20}
21
22f u n c
23 a
24 r e t u r n
25}
26
27f u n c
28 r e t u r n
29}
30
31f u n c
32 r e t u r n
33}
34
35f u n c
36 x
37 x
38
39 f m t
40
41 x
42 b
43 n
44 f m t
45
46 x
47
48 f m t
49}
Code 7:
Eective Go Jongseok Choi 77 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Outline
1
Introduction
Example
2
Formatting
3
Commentary
4
Names
Package names
Getters
Interface names
MixedCaps
5
Semicolons
6
Control structures
If
Reassignment
For
Switch
Type switch
7
Functions
Multiple return values
Named results
Defer
8
Data
Allocation with new
Constructors
Allocation with make
Arrays
Slices
Two-dimensional slices
Maps
Printing
Append
9
Initialization
Constants
Variables
init function
10
Method
Pointer vs. values
11
Interfaces and other types
Interfaces
Type assertions
Generality
12
The blank identier
Multiple assignment
Unused variables
Import for side eect
Interface checks
13
Embedding
14
Concurrency
Communicating
Goroutines
Channels
Channels of channels
15
Errors
Panic
Recover
16
A web server
Eective Go Jongseok Choi 78 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Communicating
Share by communicating
Go encourages a dierent approach in which shared values are passed around on
channels and, in fact, never actively shared by separate threads of execution.
This approach can be taken too far.
Reference counts may be best done by putting a mutex around an integer variable.
But as a high-level approach,
clear, correct programs.
One way to think about this model is to consider
program running on one CPU.
It has
Now let those two communicate.
If the communication is the synchronizer, there's still no need for other synchronization.
Unix pipelines
A slogan
Do not communicate by sharing memory; instead, share memory by communicating.
Eective Go Jongseok Choi 79 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Goroutines
Goroutines
A goroutine has a simple model
it is a function executing concurrently with other goroutines in the same address
space.
Goroutines are multiplexed onto multiple OS threads so if one should block, such
as while waiting for I/O, others continue to run.
1f u n c
2 go
3 t i m e
4 f m t
5 } ( )/ /
6}
Eective Go Jongseok Choi 80 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Channels
Channels
Kinds of chennels
Buered channel
Unbuered channel
1ci / /
2cj / /
3cs / /
4
5c / /
6/ /
7go
8 l i s t
9 c / /
10} ( )
11d o S o m e t h i n g F o r A W h i l e
12< - / /
Eective Go Jongseok Choi 81 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Channels
Channels
A buered channel can be used like a semaphore
incoming requests are passed to handle
and then receives a value from the channel to ready the \semaphore" for the next
consumer.
The capacity of the channel buer limits the number of simultaneous calls to
process.
1v a r
2
3f u n c
4 s e m / /
5 p r o c e s s / /
6 < - / /
7}
8
9f u n c
10 f o r
11 r e q
12 go / /
13 }
14}
Eective Go Jongseok Choi 82 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Channels of channels
Channels of channels
One of the most important properties of Go is that a channel is a rst-class value
handle was an idealized handler for a request but we didn't dene the type it was
handling.
If that type includes a channel on which to reply, each client can provide its own
path for the answer.
1t y p e
2 a r g s
3 f
4 r e s u l t C h a n
5}
6
7f u n c
8 f o r
9 s
10 }
11 r e t u r n
12}
13
14r e q u e s t
15c l i e n t R e q u e s t s
16f m t
1f u n c
2 f o r
3 r e q
4 }
5}
Eective Go Jongseok Choi 83 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Outline
1
Introduction
Example
2
Formatting
3
Commentary
4
Names
Package names
Getters
Interface names
MixedCaps
5
Semicolons
6
Control structures
If
Reassignment
For
Switch
Type switch
7
Functions
Multiple return values
Named results
Defer
8
Data
Allocation with new
Constructors
Allocation with make
Arrays
Slices
Two-dimensional slices
Maps
Printing
Append
9
Initialization
Constants
Variables
init function
10
Method
Pointer vs. values
11
Interfaces and other types
Interfaces
Type assertions
Generality
12
The blank identier
Multiple assignment
Unused variables
Import for side eect
Interface checks
13
Embedding
14
Concurrency
Communicating
Goroutines
Channels
Channels of channels
15
Errors
Panic
Recover
16
A web server
Eective Go Jongseok Choi 84 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Errors
Library routines must often return some sort of error indication to the caller.
Go's multivalue return makes it easy to return a detailed error description
alongside the normal return value.
By convention, errors have type error, a simple built-in interface.
1t y p e
2 E r r o r
3}
Eective Go Jongseok Choi 85 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Path error
A library writer is free to implement this interface with a richer model under the covers
Making it possible not only to see the error but also to provide some context.
As mentioned, alongside the usual*os.Filereturn value,os.Openalso returns
an error value:os.PathError.
1/ /
2/ /
3t y p e
4 Op / /
5 P a t h / /
6 E r r / /
7}
8
9f u n c
10 r e t u r n
11}
Eective Go Jongseok Choi 86 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Error example
Callers that care about the precise error details can use a type switch or a type
assertion to look for specic errors and extract details.
For PathErrors this might include examining the internal Err eld for recoverable
failures.
The second if statement here is another type assertion.
1f o r
2 file
3 if
4 r e t u r n
5 }
6 if
7 d e l e t e T e m p F i l e s / /
8 c o n t i n u e
9 }
10 r e t u r n
11}
Eective Go Jongseok Choi 87 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Panic
Panic
The usual way to report an error to a caller is to return an error as an extra return
value.
The canonical Read method is a well-known instance.
But what if the error is unrecoverable? Sometimes the program simply cannot
continue.
For this purpose, there is a built-in function panic that in eect creates a run-time error
that will stop the program.
The function takes a single argument of arbitrary type to be printed as the
program dies.
It's also a way to indicate that something impossible has happened, such as
exiting an innite loop.
1/ /
2f u n c
3 z / /
4 f o r
5 p r e v z
6 z
7 if
8 r e t u r n
9 }
10 }
11 / /
12 p a n i c
13}
Eective Go Jongseok Choi 88 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Panic
Panic
One possible counterexample is during initialization.
1i m p o r t
2
3v a r
4
5f u n c
6 if
7 p a n i c
8 }
9}
Eective Go Jongseok Choi 89 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Recover
Recover
When panic is called, including implicitly for run-time errors such as indexing a slice
out of bounds or failing a type assertion,
It immediately stops execution of the current function.
It begins unwinding the stack of the goroutine.
Running any deferred functions along the way.
If that unwinding reaches the top of the goroutine's stack, the program dies.
However, it is possible to use the built-in function recover to regain control of the
goroutine and resume normal execution.
Eective Go Jongseok Choi 90 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Recover
Recover
A call torecoverstops the unwinding and returns the argument passed topanic.
Because the only code that runs while unwinding is inside deferred functions,
recoveris only useful inside deferred functions.
One application ofrecoveris to shut down a failing goroutine inside a server
without killing the other executing goroutines.
1i m p o r t
2
3f u n c
4 f o r
5 go
6 }
7}
8
9f u n c
10 d e f e r
11 if
12 l o g
13 }
14 } ( )
15 do
16}
Eective Go Jongseok Choi 91 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Recover
Recover
Let's look at an idealized version of a regexp package, which reports parsing errors by
calling panic with a local error type.
If doParse panics, the recovery block will set the return value tonil.
1/ /
2t y p e
3
4f u n c
5 r e t u r n
6}
7
8/ /
9/ /
10f u n c
11 p a n i c
12}
13
14/ /
15f u n c
16 r e g e x p
17 / /
18 d e f e r
19 if
20 r e g e x p / /
21 e r r / /
22 }
23 } ( )
24 r e t u r n
25}
Eective Go Jongseok Choi 92 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Recover
Re-panic
re-panicidiom changes the panic value if an actual error occurs.
It does not exposepanicsto its client.
However, both the original and new failures will be presented in the crash report,
so the root cause of the problem will still be visible.
If you want to display only the original value, you can write a little more code to
lter unexpected problems andre-panicwith the original error.
Eective Go Jongseok Choi 93 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
Outline
1
Introduction
Example
2
Formatting
3
Commentary
4
Names
Package names
Getters
Interface names
MixedCaps
5
Semicolons
6
Control structures
If
Reassignment
For
Switch
Type switch
7
Functions
Multiple return values
Named results
Defer
8
Data
Allocation with new
Constructors
Allocation with make
Arrays
Slices
Two-dimensional slices
Maps
Printing
Append
9
Initialization
Constants
Variables
init function
10
Method
Pointer vs. values
11
Interfaces and other types
Interfaces
Type assertions
Generality
12
The blank identier
Multiple assignment
Unused variables
Import for side eect
Interface checks
13
Embedding
14
Concurrency
Communicating
Goroutines
Channels
Channels of channels
15
Errors
Panic
Recover
16
A web server
Eective Go Jongseok Choi 94 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
A web server
1p a c k a g e
2
3i m p o r t
4 "
5 "
6 "
7 "
8)
9
10v a r / /
11
12v a r
13
14f u n c
15 f l a g
16 h t t p
17 e r r
18 if
19 l o g
20 }
21}
22
23f u n c
24 t e m p l
25}
26
27c o n s t
28{{
29<
30{ { . } }
31<
32{{
33<
34n a m e
35v a l u e
Eective Go Jongseok Choi 95 / 95
IntroductionNamesControl structuresFunctionsData InitializationMethodInterfaces and other typesThe blank identierConcurrencyErrors
API
HTTP
JSON
Eective Go Jongseok Choi 95 / 95