SlideShare une entreprise Scribd logo
Marco Sabatini
Senior Software Engineer
sabatini.m@gmail.com
https://it.linkedin.com/in/sabatinimarco
Contacts
1
The GO Programming Language
2
Agenda
Agenda 1° Day
• Overview
• Variable types overview and scope
• Environment setup
• Packages
• Exercises
Agenda 3° Day
• Concurrent programming
• File Handling
• Linking C shared libs
• Exercises
Agenda 2° Day
• Pointers
• Collections
• Procedural programming
• Struct
• Interfaces
• Exercises
3
Agenda 4°Day
• Gorilla web toolkit
• Gorm
• Exercises
Agenda 1° Day
Agenda
• Overview
• Variable types overview and scope
• Environment setup
• Packages
• Exercises
4
Overview (authors)
• Go, also commonly referred to as golang, is a programming
language initially developed at Google in 2007 by Robert
Griesemer, Rob Pike, and Ken Thompson.
• It is a statically-typed language with syntax loosely derived
from that of C, adding garbage collection, type safety, some
dynamic-typing capabilities, additional built-in types such as
variable-length arrays and key-value maps, and a large
standard library.
•Go programs are “compiled” rather than interpreted so as to
have the best possible performance.
5
Overview (Google has big problems)
Go is a programming language designed by Google to help
solve Google’s problems.
What problems?
• C++ for servers, plus lots of Java and Python
• thousand of engineers
• gazillions of lines of code
• distributed build system
• gazillions of machines, which are treated as a modest
number of compute clusters
6
Overview (The reason of go)
Goals:
• eliminate slowness
• eliminate clumsiness
• improve effectiveness
• maintain (even improve) scale
Go was designed by and for people who write – read – debug
– maintain, large software systems.
Go’s purpose is not research programming language
design.
Go’s purpose is to make its designers’ programming lives better.
7
Overview (Who uses)
8
Overview (project status from Google)
•Go became a public open source project on November 10, 2009. After a
couple of years of very active design and development, stability was called
for and Go 1 was released on March 28, 2012. Go 1, which includes a
language specification, standard libraries, and custom tools, provides a
stable foundation for creating reliable products, projects, and publications.
•With that stability established, we are using Go to develop programs,
products, and tools rather than actively changing the language and
libraries. In fact, the purpose of Go 1 is to provide long-term stability.
Backwards-incompatible changes will not be made to any Go 1 point
release. We want to use what we have to learn how a future version of Go
might look, rather than to play with the language underfoot
•Of course, development will continue on Go itself, but the focus will be on
performance, reliability, portability and the addition of new functionality
such as improved support for internationalization.
9
Overview (important stuff)
• Object oriented without inheritance
• Syntax sugar declaration
• Strong and Static types
• Interfaces, but no declaration (duck typing)
• Functions and Methods (with receivers)
• Visibility with the first letter of symbol
• No exceptions (error interface)
• Unused imports and variables occurs compile error
• Excellent and complete standard library
10
Overview (go is a tool)
11
Overview (cross compilation)
12
Overview (let’s start coding…)
// hello.go
package main
import ( ➊ "fmt"
"os"
"strings"
)
func main() {
who := "World!" ➋
if len(os.Args) > 1 { /* os.Args[0] is "hello" or "hello.exe" */ ➌
who = strings.Join(os.Args[1:], " ") ➍ }
fmt.Println("Hello", who) ➎ }
Go uses C++-style comments: // for single-line
comments that finish at the end of the line and /* ...
*/ for comments that can span multiple lines.
Every piece of Go code exists inside a package, and
every Go program must have a main package with a
main() function which serves as the program’s entry
point, that is, the function that is executed first.
The import statement (➊) imports three packages
from the standard library.
The first statement in the main() function (➋; using the :=
operator) is called a short variable declaration in Go
terminology.
The os.Args variable is a slice of strings (➌).
If the user has entered one or more command line
arguments the if condition is satisfied and we set the who
string to contain all the arguments joined up as a single
string (➍).
Finally, in the last statement (➎), we print Hello, a space,
the string held in the who variable, and a newline.
13
Syntax overview 1/2
• Basically C-like with reversed types and declarations,
plus keywords to introduce each type of declaration.
• Basic control structures are familiar:
• Note: no parentheses, but braces required.
14
Syntax overview 2/2
Semicolons terminate statements but:
• lexer inserts them automatically at end of line if the previous token could
end a statement.
• Note: much cleaner, simpler than JavaScript rule!
Thus no semis needed in this program:
In practice, Go code almost never has semicolons outside for and if clauses
15
Declaration
Declarations are introduced by a keyword (var, const,
type, func) and are reversed compared to C:
Why are they reversed? Earlier example:
• Both p and q have type *int.
• Also functions read better and are consistent with other
declarations. 16
Var Identifier
• Variable declarations are introduced by “var” identifier.
• They may have a type or an initialization expression;
• One or both must be present.
• Initializers must match variables (and types!).
17
Distributing Var
Annoying to type var all the time. Group with parens:
Applies to const, type, var but not func!!!
18
The := “short declaration”
Within functions (only), declarations of the form:
can be shortened to:
(Another reason for the name/type reversal.)
The type is that of the value (for ideal numbers, get int or
float64 or complex128, accordingly.)
These are used a lot and are available in places such
as for loop initializers.
19
Const
• Constant declarations are introduced by const.
• They must have a "constant expression", evaluated at compile
time, as initialiser and may have an optional type specifier.
20
Iota
Constant declarations can use the counter iota, which
starts at 0 in each const block and increments at each
implicit semicolon (end of line).
Shorthand: Previous type and expressions repeat.
21
Type
Type declarations are introduced by type. We'll learn more
about types later but here are some examples:
22
New
The built-in function new allocates memory. Syntax is like
a function call, with type as argument, similar to C++.
Returns a pointer to the allocated object (pointers )
Later we'll see how to build slices and such.
There is no delete or free; Go has garbage collection.
23
Assignment
Assignment is easy and familiar:
But multiple assignment works too:
Functions can return multiple values (details later):
24
If
Basic form is familiar, but no dangling else problem:
Initialization statement allowed; requires semicolon.
Useful with multivariate functions:
Missing condition means true, which is not too useful in this
context but handy in for, switch.
25
For
Basic form is familiar:
Missing condition means true:
But you can leave out the semis too:
Don't forget multivariate assigments:
26
Switch 1/2
Switches are somewhat similar to C's.
But there are important syntactic and semantic differences:

- expressions need not be constant or even int.
- no automatic fall through

- instead, lexically last statement can be fall-through
- multiple cases can be comma-separated
27
Switch 2/2
Go's switch is more powerful than C's. Familiar form:
The expressions can be any type and a missing switch
expression means true. Result: if-else chain:
or
28
Break and continue …
The break and continue statements work as in C. They
may specify a label to affect an outer structure:
29
Agenda 1° Day
Agenda
• Overview
• Variable types overview and scope
• Environment setup
• packages
• Exercises
30
Go Typing
• Go is a statically typed programming language. This
means that variables always have a specific type and
that type cannot change.
• Static typing may seem cumbersome at first. You'll spend
a large amount of your time just trying to fix your
program so that it finally compiles. But types help us
reason about what our program is doing and catch a
wide variety of common mistakes.
• Go comes with several built-in data types which we will
now look at in more detail.
31
Numeric 1/3
A. Generally we split numbers into two different kinds:
integers and floating-point numbers.
• Go's integer types are: uint8, uint16, uint32, uint64,
int8, int16, int32 and int64. 8, 16, 32 and 64 tell us
how many bits each of the types use.
• In addition there two alias types: byte which is the
same as uint8 and rune which is the same as int32.
• There are also 3 machine dependent integer types: uint, int
and uintptr. They are machine dependent because their
size depends on the type of architecture you are using.
32
Numeric 2/3
• Floating point numbers are numbers that contain a decimal component
(real numbers). (1.234, 123.4, 0.00001234, 12340000)
• Like integers floating point numbers have a certain size (32 bit or 64 bit).
Using a larger sized floating point number increases it's precision. (how
many digits it can represent)
• In addition to numbers there are several other values which can be
represented: “not a number” (NaN, for things like 0/0) and positive and
negative infinity. (+∞ and −∞)
• Go has two floating point types: float32 and float64
• Additional types for representing complex numbers (numbers with
imaginary parts): complex64 and complex128
33
Numeric 3/3
Summary
34
String 1/2
• Go strings are made up of individual bytes, usually one
for each character. (Characters from other languages
like Chinese are represented by more than one byte)
• String literals can be created using double quotes
"Hello World" or back ticks `Hello World`.
• Common operations:
• len(“Hello World!!!”)
• “Hello World”[1] (access individual char)
• “Hello ”+”World!!!” (string concatenation)
• Examples!!!
35
String 2/2
String memory organization
36
Boolean
A boolean value (named after George Boole) is a special
1 bit integer type used to represent true and false (or
on and off). Three logical operators are used with
boolean values:
37
Agenda 1° Day
Agenda
• Overview
• Variable types overview and scope
• Environment setup
• packages
• Exercises
38
Golang Setting programming environment 1/2
Compiler&Runtime
• https://golang.org/doc/install (package download web
pages)
• export GOPATH=$HOME/go (environment variable to
store GO base path)
• export PATH=$PATH:$GOPATH/bin (add “GO”
runtime binary to path)
39
Golang Setting programming environment 2/2
IDE
• GoClipse is an Eclipse IDE for the Go programming language. The purpose of
GoClipse is to create an environment in which development of Go is easy for a
beginner to intermediate user.
• https://goclipse.github.io ( documentation and download link )
• Code completion ( setting GOPATH )
• Source navigation
• Compilation
• Execution (Run As)
• Debugging (Debug As)
40
Agenda 1° Day
Agenda
• Overview
• Variable types overview and scope
• Environment setup
• Packages
• Exercises
41
Golang source code project structure
Go code must be kept inside a workspace.
A workspace is a directory hierarchy with three directories at its root:
• root_project
• src
• bin
• pkg
then you have to export this env variables:
export GOROOT=/usr/local/go
export GOPATH=~/workspace/me/go
export PATH=$PATH:$GOROOT/bin:$GOPATH/bin
build: “go install”
42
Golang packages&docs
Packages only really make sense in the context of a
separate program which uses them.
• Execute “go install”
creates average.a
linkable object file.
• Can reuse your code
Example of documentation:
godoc average_kg
godoc -http:”6060”
Golang has a large number of precompiled packages we can use in our
software!!!
43
Testing code
• simple_test_example: go test simple_test_example
• bench_test_example: go test bench_test_example
44
Agenda 1° Day
Agenda
• Overview
• Variable types overview and scope
• Environment setup
• packages
• Exercises
45
Exercises
1. reverse a string ascii and utf8
2. packaging reverse string ascii&utf8 func
3. pattern match (find email in a text)
4. packaging pattern match email func
5. pass values from CLI to previous exercises (args)
6. pass values from CLI to previous exercises (flags
pkg)
7. fmt.Scanf (read doc and use it)
8. remove duplicates char in a string
46
Agenda 2° Day
Agenda
• Pointers
• Collections
• Procedural programming
• Struct
• Interfaces
• Exercises
47
Pointers Overview 1/2
When we call a function that takes an argument, that
argument is copied to the function:
In this program the zero function will not modify the original x
variable in the main function. But what if we wanted to? One
way to do this is to use a special data type known as a pointer
48
Pointers Overview 2/2
Pointers reference a location in memory where a value is
stored rather than the value itself. (They point to
something else) By using a pointer (*int) the zero
function is able to modify the original variable.
49
‘*’ and ‘&’ operators 1/2
1. In Go a pointer is represented using the * (asterisk)
character followed by the type of the stored value.
2. ‘*’ is also used to “dereference” pointer variables.
Dereferencing a pointer gives us access to the value the
pointer points to.
3. *xPtr = 0 we are saying “store the int 0 in the memory
location xPtr refers to”.
4. xPtr = 0 instead we will get a compiler error because xPtr is
not an int it's a *int, which can only be given another *int.
50
‘*’ and ‘&’ operators 1/2
We use the ‘&’ operator to find the
address of a variable.
&i returns a *int (pointer to an int)
because i is an int.
This is what allows us to modify the
original variable. &i and ptr are the
same memory location.
51
The New function
Another way to get a pointer is to use the built-in new
function:
In some programming languages there is a significant difference between using new
and &, with great care being needed to eventually delete anything created with new.
Go is not like this, it's a garbage collected programming language which means
memory is cleaned up automatically when nothing refers to it anymore.
new takes a type as an
argument, allocates
enough memory to fit a
value of that type and
returns a pointer to it.
52
Garbage Collector
Go 1 > 1.4 has used a parallel stop-the-world (STW) collector. While STW collection
has many downsides, it does at least have predictable and controllable heap growth
behavior. The sole tuning knob for the STW collector was “GOGC”, the relative heap
growth between collections. The default setting, 100%, triggered garbage collection
every time the heap size doubled over the live heap size as of the previous collection
Go 1.5 will introduce a concurrent collector.
53
Agenda 2° Day
Agenda
• Pointers
• Collections
• Procedural programming
• Struct
• Interfaces
• Exercises
54
Arrays
An array is a numbered sequence of elements of a
single type with a fixed length.
In Go they look like this:
declares “ar” to be an array of 3 integers, initially all
set to zero.
Size is part of the type. Built-in function len reports size:
55
Arrays literals
All the composite types have similar syntax for creating
values. For arrays it look like this:
Array of 3 integers:
Array of 10 integers, first three not zero:
Don't want to initialize them all? Use key:value pairs:
56
Arrays are values
Arrays are values, not implicit pointers as in C.
You can take an array's address, yielding a pointer to
the array (to pass it efficiently to a function):
Output
57
Pointers to arrays literals
You can take the address of an array literal to get a
pointer to a newly created instance:
Output
58
Slices
• A slice is a reference to a section of an array.
• Slices are used much more often than plain arrays.
• A slice is very cheap. (More about this soon.)
• A slice type looks like an array type without a size:
Built-in len(a) returns the number of elements.
Create a slice by "slicing" an array or slice:
Valid indexes of a will then be 0 and 1; len(a)==2.
59
Slice shorthands
When slicing, first index defaults to 0:
ar[:n] means the same as ar[0:n].
Second index defaults to len(array/slice):
ar[n:] means the same as ar[n:len(ar)].
Thus to create a slice from an array:
ar[:] means the same as ar[0:len(ar)].
60
A slices references an array
Conceptually
61
Making Slices
Slice literals look like array literals without a size:
What this does is create an array of length 5 and then create a slice
to refer to it.
We can also allocate a slice (and underlying array) with the built-in
function make:
• Why make not new? Because we need to make a slice, not
just allocate the memory.
• Note make([]int, 10) returns []int while new([]int) returns *[]int.
• Use make to create slices, maps, and channels.
62
Slices capacity
A slice refers to an underlying array, so there may be
elements off the end of the slice that are present in the
array.
The built-in function cap (capacity) reports how long the
slice could possibly grow after.
len(a) is 2 and cap(a) is 5. We can "reslice":
len(a) is now 4 but cap(a) is still 5.
63
Resizing Slices
Slices can be used like growable arrays. Allocate one using
make with two numbers - length and capacity - and reslice as it
grows:
Thus sl's length is always the number of elements, but it
grows as needed.
This style is cheap and idiomatic in Go!!!
64
Slices are cheap
• Feel free to resize slices as required. They are cheap to pass around;
no need to allocate.
• Remember they are references, so underlying storage can be modified.
• For instance, I/O uses slices, not counts:
Split a buffer:
Strings can be sliced too, with similar efficiency. 65
Slice functions append()
Go includes two built-in functions to assist with slices:
append and copy. Here is an example of append:
After running this program slice1 has [1,2,3] and slice2
has [1,2,3,4,5]. append creates a new slice by taking
an existing slice (the first argument) and appending
all the following arguments to it.
66
Here is an example of copy:
After running this program slice1 has [1,2,3] and slice2
has [1,2]. The contents of slice1 are copied into slice2,
but since slice2 has room for only two elements only
the first two elements of slice1 are copied.
Slice functions copy()
67
Maps
Maps are another reference type.
They are declared like this:
This declares a map indexed with key type string and
value type float64. It is analogous to the C++ type
*map<string,float64> (note the *).
Given a map m, len(m) returns the number of keys.
68
Map creation
As with a slice, a map variable refers to nothing; you
must put something in it before it can be used.
Three ways:
1) Literal: list of colon-separated key:value pairs
2) Creation
3) Assignment
69
Indexing Map
Next few examples all use:
Access an element as a value; if not present, get zero
value for the map's value type:
Set an element (setting twice updates value for key)
70
Testing existence
To test if a key is present in the map, we can use a multi-
value assignment, the "comma ok" form:
or idiomatically:
If x is present in the map, sets the boolean to true and the value to the
entry for the key. If not, sets the boolean to false and the value to the
zero for its type.
71
Deleting
Deleting an entry in the map is a multi-variate assignment
to the map entry:
If keep is true, assigns v to the map; if keep is false,
deletes the entry for key x. So to delete an entry:
delete(m, x )
72
For and range (Arrays, Slices, Maps)
The for loop has a special syntax for iterating over arrays,
slices, maps (and more, as we'll see tomorrow).
With only one variable in the range, get the key:
Variables can be assigned or declared using ‘:=‘ .
For arrays and slices, get index and value.
73
Range Over String
A for using range on a string loops over Unicode code points, not
bytes. (Use []byte for bytes, or use a standard for). The string
is assumed to contain UTF-8.
If erroneous UTF-8 is encountered, the character is set
to U+FFFD and the index advances by one byte.
74
Agenda 2° Day
Agenda
• Pointers
• Collections
• Procedural programming
• Struct
• Interfaces
• Exercises
75
Functions
A function is an independent section of code that maps zero or more
input parameters to zero or more output parameters. Functions
(also known as procedures or subroutines) are often represented
as a black box: (the black box represents the function)
We will now begin writing programs that use more than
one function.
76
Your second function
This program computes the average of a series of numbers.
Finding the average like this is a very general problem, so
its an ideal candidate for definition as a function.
The average function will need to take in a slice of float64s
and return one float64. Insert this before the main function:
77
Functions (variable scope)
Functions don't have access to anything in the calling
function.
ok
okWrong
78
Functions (call stack)
Call Stack
Each time we call a function we push it onto the call stack and
each time we return from a function we pop the last function
off of the stack.
79
Returning multiple values
Go is also capable of returning multiple values from a function
Three changes are necessary:
A. change the return type to contain multiple types
separated by ,
B. change the expression after the return so that it
contains multiple expressions separated by ,
C. change the assignment statement so that
multiple values are on the left side of the := or
=.
Multiple values are often used to return an error value along with the
result (x, err := f()), or a boolean to indicate success (x, ok := f()).
80
Variadic functions
• By using “…" before the type
name of the last parameter you
can indicate that it takes zero
or more of those parameters.
• In this case we take zero or
more ints.
• We invoke the function like any
other function except we can
pass as many ints as we want.
This is precisely how the fmt.Println function is implemented:
81
Closure 1/2
It is possible to create functions inside of functions:
add is a local variable that has the
type func(int, int) int (a function that
takes two ints and returns an int).
When you create a local function like
this it also has access to other local
variables.
A function like this together with the
non-local vari- ables it references is
known as a closure. In this case
increment and the variable x form
the closure.
82
Closure 2/2
It is possible to create functions inside of functions:
• One way to use closure is
by writing a function which
returns another function.
• makeEvenGenerator returns
a function which generates
even numbers. Each time
it's called it adds 2 to the
local i variable which.
83
Recursion
Finally a function is able to call itself
No Factorial example please!!!
Some hacking on Go source code (path.go) !!!
84
Defer
Go has a special statement called defer which schedules
a function call to be run after the function completes
defer is often used when resources need to be freed in
some way. For example when we open a file we need
to make sure to close it later.
This has 3 advantages:
(1) it keeps our Close call near our Open call so its easier
to understand,
(2) if our function had multiple return statements (perhaps
one in an if and one in an else) Close will happen before
both of them and
(3) deferred functions are run even if a run-time panic
occurs.
85
Panic & Recover
We can handle a run-time panic with the built-in recover function.
Recover stops the panic and returns the value that was passed to the call to
panic.
A panic generally indicates a programmer error (for example attempting to access
an index of an array that's out of bounds, forgetting to initialize a map, etc.)
Error Ok
86
Memoization
If a pure function is expensive to compute and frequently used with the same
arguments, we can use memoization to reduce the processing overhead
The memoization technique is where we store the results of a computation
so that when the same computation is next requested we are able to return
the stored results rather than perform the computation all over again
87
Higher order function
A higher order function is a function that takes one or more other
functions as arguments and uses them in its own body.
Output?
88
Agenda 2° Day
Agenda
• Pointers
• Collections
• Procedural programming
• Structs
• Interfaces
• Exercises
89
Structs
Structs should feel very familiar: simple declarations of data
fields.
More usual:
Structs allow the programmer to define the layout of memory.
90
Structs are values
Structs are values and new(StructType) returns a pointer to a
zero value (memory all zeros).
There is no -> notation for structure pointers. Go provides the
indirection for you.
91
Making structs
Structs are values so you can make a zeroed one just
by declaring it.
You can also allocate one with new.
Struct literals have the expected syntax
As with arrays, taking the address of a struct literal gives the address
of a newly created value.These examples are constructors.
92
Exporting types and fields
The fields (and methods, coming up soon) of a struct must start
with an Uppercase letter to be visible outside the package.
Private type and fields:
Exported type and fields:
Exported type with mix of fields:
You may even have a private type with exported
fields. Exercise: when is that useful? 93
Anonymous fields
• Inside a struct, you can declare fields, such as another
struct, without giving a name for the field.
• These are called anonymous fields and they act as if
the inner struct is simply inserted or "embedded" into
the outer.
• This simple mechanism provides a way to derive some
or all of your implementation from another type or
types.
An example follows!!!
94
An anonymous struct field
B acts as if it has four fields, ax,
ay, bx, and by. It's almost as if
B is {ax, ay int; bx, by float64}.
However, literals for B must be
filled out in detail:
Prints: 1, 2, 3, 4
95
Anonymous fields have type as name
But it's richer than simple interpolation of the fields: B
also has a field A. The anonymous field looks like a
field whose name is its type.
Prints {1 2}.
If A came from another package,the field is called A:
96
Anonymous fields of any type
Any named type, or pointer to one, may be used in an
anonymous field and it may appear at any location in
the struct.
Prints 3.5 7 hello
97
Conflicts and hiding
If there are two fields with the same name (possibly a
type-derived name), these rules apply:
1) An outer name hides an inner name.

This provides a way to override a field/method.
2) If the same name appears twice at the same level, it
is an error if the name is used by the program. (If it's
not used, it doesn't matter.)
No rules to resolve the ambiguity; it must be fixed.
98
Conflict examples
Using c.a is an error: is it c.A.a or c.B.a?
Using d.b is OK: it's the float64, not d.B.b Can get at
the inner b by D.B.b.
99
Methods on struct pointers
• Go has no classes, but you can attach methods to any type.
• The methods are declared, separate from the type declaration,
as functions with an explicit receiver (like java this).
• The obvious struct case:
Note: explicit receiver (no automatic this), in this case of
type *Point, used within the method.
100
Methods on struct values
A method does not require a pointer as a receiver.
This is a bit expensive, because the Point3 will always be
passed to the method by value, but it is valid Go.
101
Invoking a methods
Just as you expect.
A non-struct example:
102
Ground rules for methods
• Methods are attached to a named type, say Foo, and
are statically bound.
• The type of a receiver in a method can be either *Foo
or Foo. You can have some Foo methods and some
*Foo methods.
• Foo itself cannot be a pointer type, although the
methods can have receiver type *Foo.
• The type Foo must be defined in the same package
as all its methods.
103
Pointers & Values
Go automatically indirects/dereferences values for you when
invoking methods.
For instance, even though a method has receiver type *Point you
can invoke it on an addressable value of type Point.
Similarly, if methods are on Point3 you can use a value
of type *Point3:
104
Methods on anonymous fields
Naturally, when an anonymous field is embedded in a
struct, the methods of that type are embedded as
well - in effect, it inherits the methods.
This mechanism offers a simple way to emulate some
of the effects of subclassing and inheritance.
105
Anonymous field example
106
Overriding a method
Overriding works just as with fields.
Of course you can have
multiple anonymous fields
with various types - a
simple version of multiple
inheritance. The conflict
resolution rules keep things
simple, though.
107
Another example
A more compelling use of an anonymous field.
Note that Lock's receiver is (the address of) the Mutex field,
not the surrounding structure. (Contrast to subclassing)
108
Other types 1/3
Methods are not just for structs. They can be defined for any
(non-pointer) type.
The type must be defined in your package though. You can't
write a method for int but you can declare a new int type and
give it methods.
109
Other types 2/3
Now we have an enumeration-like type that knows how
to print itself.
110
Other types 3/3
By techniques to be divulged soon, fmt.Print and friends
can identify values that implement the method.
String as we defined for type Day. Such values are
automatically formatted by invoking the method.
Thus:
prints 0 Monday 1 Tuesday.
Println can tell a plain 0 from a 0 of type Day.
So define a String method for your types and they will print
nicely with no more work.
111
Fileds and methods visibility
Go is very different from C++ in the area of visibility. Go's rules:
1) Go has package scope (C++ has file scope).
2) ︎Spelling determines exported/local (pub/priv).
3)︎Structs in the same package have full access to one another's
fields and methods.
4) Local type can export its fields and methods.

5) No true subclassing, so no notion of "protected".
These simple rules seem to work well in practice.
112
Agenda 2° Day
Agenda
• Pointers
• Collections
• Procedural programming
• Structs
• Interfaces
• Exercises
113
Interfaces Overview
• So far, all the types we have examined have been
concrete: they implement something.
• There is one more type to consider: the interface type.
• It is completely abstract; it implements nothing.
Instead, it specifies a set of properties an
implementation must provide.
• Interface as a concept is very close to that of Java,
and Java has an interface type, but the "interface
value" concept of Go is novel.
114
Interfaces definition
The word "interface" is a bit overloaded in Go:
1. There is the concept of an interface
2. There is an interface type
3. There are values of that type.
Definition:
An interface is a set of methods.
To turn it around, the methods implemented by a concrete
type such as a struct form the interface of that type.
115
Example
We saw this simple type before:
The interface of type Point has the method:
It's not
because the interface abstracts away the receiver.
We embedded Point in a new type, NamedPoint;
NamedPoint has the same interface.
116
The interface type
An interface type is a specification of an interface, a set
of methods implemented by some other types. Here's
a simple one, with only one method:
This is a definition of the interface implemented by Point,
or in our terminology,
Point implements Abs Interface
Also, NamedPoint and Point3 implement Abs Interface
Methods are written inside the interface declaration.
117
Example
MyFloat implements AbsInterface even though
float64 does not.
(Aside: MyFloat is not a "boxing" of float64; its
representation is identical to float64.)
118
Interface embedding
Interfaces can embed other interfaces and the effect is al-
most the same as if we had written the embedded
interface’s method signatures in the interface that embeds it
119
Interface value
Once a variable is declared with interface type, it may
store any value that implements that interface.
120
In memory
ai is not a pointer! It's a multiword data structure.
At different times it has different value and type:
121
Summary
1) Interfaces define sets of methods. They are pure and
abstract: no implementation, no data fields. Go has a
clear separation between interface and implementation.
2) Interface values are just that: values. They contain any
concrete value that implements all the methods defined in
the interface. That concrete value may or may not be a
pointer.
3) Types implement interfaces just by having methods.
They do not have to declare that they do so. For instance,
every type implements the empty interface, interface{}.
122
Example io.Writer
Here is the actual signature of fmt.Fprintf:
It doesn't write to a file, it writes to something of type io.Writer,
that is, Writer defined in the io package:
Fprintf can therefore be used to write to any type that
has a canonical Write method, including files, pipes,
network connections, and...
123
Example Buffered I/O
... a write buffer. This is from the bufio package:
bufio.Writer implements the canonical Write method.
It also has a factory: give it an io.Writer, it will return a
buffered io.Writer in the form of a bufio.Writer:
And of course, os.File implements Writer too.
124
Putting it together
Buffering works for anything that Writes.
Feels almost like Unix pipes, doesn't it? The
composability is powerful; see crypto packages.
125
Other public interfaces in io
The io package has:
Reader
Writer
ReadWriter
ReadWriteCloser
These are stylized interfaces but obvious: they capture the
functionality of anything implementing the functions listed in
their names.
This is why we can have a buffered I/O package with an
implementation separate from the I/O itself: it both accepts and
provides interface values.
126
Comparison
In C++ terms, an interface type is like a pure abstract
class, specifying the methods but implementing none
of them.
In Java terms, an interface type is much like a Java
interface.
However, in Go there is a major difference:

A type does not need to declare the interfaces it
implements, nor does it need to inherit from an
interface type. If it has the methods, it implements the
interface.
127
Anonymous fields work too
LockedBufferedWriter implements io.Writer, but also,
through the anonymous Mutex,
128
HTTP service example
This is the interface defined by the HTTP server package. To
serve HTTP, define a type that implements this interface and
connect it to the server (details omitted).
129
A function that serves HTTP
Now we define a type to implement ServeHTTP:
Convert function to attach method, implement the interface:
130
Containers & the empty interface
Sketch of the implementation of vectors. (In practice,
tend to use raw slices instead, but this is informative):
Vectors can contain anything because any type implements the
empty interface. (In fact every element could be of different
type.)
131
Type assertions
Once you put something into a Vector, it's stored as an interface
value. Need to "unbox" it to get the original back: use a "type
assertion". Syntax:
Will fail if type is wrong - but see next slide.
Type assertions always execute at run time. Compiler
rejects assertions guaranteed to fail.
132
Interface to interface conversion
So far we've only moved regular values into and out of
interface values, but interface values that contain the
appropriate methods can also be converted.
In effect, it's the same as unboxing the interface value
to extract the underlying concrete value, then boxing
it again for the new interface type.
The conversion's success depends on the underlying
value, not the original interface type.
133
Interface to interface example
Given:
These are all OK:
134
Testing with type assertions
Can use "comma ok" type assertions to
test a value for type.
135
Testing with a type switch
Special syntax:
136
Does v implement m()?
Going one step further, can test whether a
value implements a method.
This is how Print etc. check if type can print itself.
137
Reflection and …
There is a reflection package (reflect) that builds on these ideas to let you
examine values to discover their
type. Too intricate to describe here but Printf etc. use it to analyze the its
arguments.
Inside Printf, the args variable becomes a slice of the
specified type, i.e. []interface{}, and Printf uses the
reflection package to unpack each element to analyze its
type.
138
Reflection and Print
As a result, Printf and its friends know the actual types of their arguments.
Because they know if the
argument is unsigned or long, there is no %u or %ld, only %d.
This is also how Print and Println can print the arguments nicely without a format
string.
There is also a %v ("value") format that gives default nice output from Printf for
values of any type.
Prints -1 hello [1 2 3] 456.

In fact, %v is identical to the formatting done by Print
and Println
139
Agenda 2° Day
Agenda
• Pointers
• Collections
• Procedural programming
• Structs
• Interfaces
• Exercises
140
Exercise
1. swap var
2. sort int array
3. sort string array
4. make append function for slice
5. circular linked list
6. stack
141
Agenda 3° Day
Agenda
• Concurrent programming
• File Handling
• Linking C shared libs
• Exercises
142
Goroutines
Terminology:
There are many terms for "things that run concurrently"
- process, thread, POSIX thread, NPTL thread,
lightweight process, ..., but these all mean slightly
different things. None means exactly how Go does
concurrency.
So we introduce a new term: goroutine.
143
Definition
A goroutine is a Go function or method executing
concurrently in the same address space as other
goroutines. A running program consists of one or
more goroutines.
It's not the same as a thread, process, etc. It's a
goroutine.
Note: Concurrency and parallelism are different
concepts. Look them up if you don't understand the
difference.
144
Starting a goroutine
Invoke a function or method and say go:
Prints???
145
Some simple facts
Goroutines are cheap.
Goroutines exit by returning from their top-level
function, or just falling off the end.
Goroutines can run concurrently on different
processors, sharing memory.
You don't have to worry about stack size.
146
Stacks
In gccgo, at least for now, goroutines are pthreads. In 6g
they're multiplexed onto threads, so they are much
cheaper.
In both worlds, stacks are small (a few kB) and grow as
needed.
Thus goroutines use little memory, you can have lots of
them, and they can dynamically have huge stacks.
The programmer shouldn't have to think about the stack
size issue, and in Go, it doesn't even come up.
147
Scheduling
Goroutines are multiplexed as needed onto system threads.
When a goroutine executes a blocking system call, no
other goroutine is blocked.
Plan to do the same for CPU-bound goroutines at some
point, but for now, if you want user - level parallelism in 6g*
you must set shell var:
GOMAXPROCS or call runtime.GOMAXPROCS(n).
GOMAXPROCS tells the runtime scheduler how many user-
space-executing goroutines to run at once, ideally on
different CPU cores.
*gccgo always uses one thread per goroutine.
148
Scheduling
149
Scheduling
150
Thread communication (Channels)
Unless two goroutines can communicate, they can't
coordinate.
Go has a type called a channel that provides
communication and synchronization capabilities.
It also has special control structures that build on
channels to make concurrent programming easy.
151
Channel type
In its simplest form the type looks like this:
With a value of this type, you can send and receive items of
elementType.
Channels are a reference type, which means if you assign one
chan variable to another, both variables access the same
channel. It also means you use make to allocate one:
152
The communication operator: <-
The arrow points in the direction of data flow.
As a binary operator, <- sends the value on the right to
the channel on the left:
As a prefix unary operator, <- receives from a channel:
153
Semantics
By default, communication is synchronous. (We'll talk about
asynchronous communication later.) This means:
1) A send operation on a channel blocks until a receiver is
available for the same channel.
2) A receive operation for a channel blocks until a sender is
available for the same channel.
Communication is therefore a form of synchronization: two
goroutines exchanging data through a channel
synchronized at the moment of communication.
154
Let’s pump some data
Now we start a
looping receiver.
You can still sneak in
and grab a value:
155
Functions returning channels
In the previous example, pump was like a generator
spewing out values. But there was a lot of fuss allocating
channels etc. Let's package it up into a function returning the
channel of values.
156
Range & Channels
The range clause on for loops accepts a channel as an operand,
in which case the for loops over the values received from the
channel. We rewrote pump; here's the rewrite for suck, making
it launch the goroutine as well:
157
Closing channel
How does range know when the channel is done
delivering data? The sender calls the built-in
function close: close(ch)
Receiver tests if the sender has closed the channel
using "comma ok":
val, ok := <-ch


Result is (value, true) while values are available;
once channel is closed and drained, result is (zero,
false).
158
Range on a channel, by hand
A for range on a channel such as:
is equivalent to:
159
Close
Only the sender should call close.

Only the receiver can ask if channel has been closed.
Can only ask while getting a value (avoids races).
Call close only when it's necessary to signal to the
receiver that no more values will arrive.
Most of the time, close isn't needed; it's not analogous
to closing a file.
Channels are garbage-collected regardless.
160
Channel directionality 1/2
In its simplest form a channel variable is an unbuffered
(synchronous) value that can be used to send and receive.
A channel type may be annotated to specify that it may only
send or only receive:
161
Channel directionality 2/2
All channels are created bidirectional, but we can assign them to
directional channel variables. Useful for instance in functions,
for (type) safety:
162
Synchronous channel
Output:
sending 10 (happens immediately)
sent 10 (60s later, these 2 lines appear)
received 10
163
Asynchronous channels
A buffered, asynchronous channel is created by telling
make the number of elements in the buffer.
Output:
sending 10 (happens
immediately)
sent 10 (now)
received 10 (60s later)
164
Buffer is not part of the type
Note that the buffer's size, or even its existence, is not
part of the channel's type, only of the value. This code is
therefore legal, although dangerous:
Buffering is a property of the value, not of the type.
165
Unbuffered chan
166
Buffered chan
167
Select
Select is a control structure in Go analogous to a
communications switch statement. Each case must
be a communication, either send or receive.
Select executes one runnable case at random. If no case is runnable, it blocks
until one is. A
default clause is always runnable.
168
Random bit generator
Prints 0 1 1 0 0 1 1 1 0 1 ...
169
Testing for communicability
Can a communication proceed without blocking? Select
with a default clause can tell us:
The default clause executes if no other case can
proceed, so this is the idiom for non-blocking
receive; non-blocking send is the obvious variant.
170
Timeout
Can a communication succeed in a given interval? Package
time contains the After function:
It delivers a value (the current time) on the returned channel
after the specified interval.
Use it in select to implement timeout:
171
Multiplexing
Channels are first-class values, which means they can
be sent over channels. This property makes it easy to
write a service multiplexer since the client can supply,
along with its request, the channel on which to reply,
Or more typically
172
Multiplexing server
173
Starting the server
Use the "function returning channel" idiom to create a
channel to a new server:
174
The client
A similar example is worked in more detail in the tutorial,
but here's a variant:
Requests are ready; send them:
Can retrieve results in any order; r.replyc demuxes:
175
Teardown
In the multiplex example, the server runs forever. To
tear it down cleanly, signal with a channel. This server
has the same functionality but with a quit channel:
176
Starting the server
The rest of the code is mostly the same, with an extra channel:
177
Teardown: the client
The client is unaffected until it's ready to shut down the server:
All done, signal server to exit:
178
Concurrency issues
Many issues, of course, but Go tries to take care of
them. Channel send and receive are atomic. The
select statement is very carefully defined and
implemented, etc.
But goroutines run in shared memory, communication
networks can deadlock, multithreaded debuggers
suck, and so on.
What to do?
179
Go primitives
Don't program the way you would in C or C++ or even
Java.
Channels give you synchronization and communication
both, and that makes them powerful but also easy to
reason about if you use them well.
The rule is:
Do not communicate by sharing memory. Instead,
share memory by communicating.
The very act of communication guarantees
synchronization!
180
Agenda 3° Day
Agenda
• Concurrent programming
• File Handling
• Linking C shared libs
• Exercises
181
Go: I/O
• The two main interfaces are Reader and Writer.
• Many functions in Go take Readers or Writers as arguments.
• For example the io package has a Copy function which
copies data from a Reader to a Writer
To read or write to a []byte or a string you can use the Buffer
struct found in the bytes package:
182
Files: basic operations: read 1/2
Open & read file
183
Files: basic operations: read 2/2
There's a shorter way to read a file
184
Files: basic operations: create
Create a file “test.txt” and
write test in content
185
Files: basic operations: read a directory 1/2
Read directory “.” and
get file infos
186
Read directory
recursively using
path/filepath package
Agenda 3° Day
Agenda
• Concurrent programming
• File Handling
• Linking C shared libs
• Exercises
188
cgo 1/2
• Cgo enables the creation of Go packages that call C
code.
• To use cgo write normal Go code that imports a
pseudo-package "C".
189
cgo 1/2
package main
/*
#cgo CFLAGS: -I./
#cgo LDFLAGS: -L. -lkeyboard
#include <keyboard.h>
*/
import "C"
import (
"fmt"
)
func main() {
C.InitKeyboard()
fmt.Printf("nEnter: ")
for {
r := C.GetCharacter()
fmt.Printf("%c", r)
if r == 'q' {
break
}
}
C.CloseKeyboard()
}
1. CFLAGS:parameters to the
compiler.
2. ./ folder: compilercan find our
header files.
3. LDFLAGS: parameters to the
linker.
4. -L: (minus capital L) which tells
the linker where it can find
our dynamic library
5. -l: (minus lowercase L) which
tells the linker the name of
our library.
190
Agenda 3° Day
Agenda
• Concurrent programming
• File Handling
• Linking C shared libs
• Exercises
191
Exercises
• Read dir
• Analize file extension
• apply regular expression file
content
• multithread mode
192
Agenda 4° Day
Agenda
• Gorilla web toolkit (Go Web Application Toolkit)
• Gorm (Go ORM)
• Exercises
193
Overview
Web Toolkit build with go
• gorilla/context: stores global request variables.
• gorilla/mux: is a powerful URL router and dispatcher.
• gorilla/reverse: produces reversible regular expressions for regexp-based muxes.
• gorilla/rpc: implements RPC over HTTP with codec for JSON-RPC.
• gorilla/schema: converts form values to a struct.
• gorilla/securecookie encodes and decodes authenticated and optionally encrypted
cookie values.
• gorilla/sessions: saves cookie and filesystem sessions and allows custom session
backends.
• gorilla/websocket: implements the WebSocket protocol defined in RFC 6455.
194
Installation
195
Simple Web Application
GorillaToolkitAppTest
196
Agenda 4° Day
Agenda
• Gorilla web toolkit (Go Web Application Toolkit)
• Gorm (Go ORM)
• Exercises
197
Overview
Gorm is ORM (Object Relational Mapper) library for Golang
• Full-Featured ORM (almost)
• Chainable API
• Auto Migrations
• Relations (Has One, Has Many, Belongs To, Many To Many, Polymorphism)
• Callbacks (Before/After Create/Save/Update/Delete/Find)
• Preloading (eager loading)
• Transactions
• Embed Anonymous Struct
• Soft Deletes
• Customizable Logger
• Iteration Support via Rows
• Every feature comes with tests
• Developer Friendly
198
Installation
Gorm toolkit: go get -u github.com/jinzhu/gorm
Postgresql driver: go get github.com/lib/pq
Gorilla web toolkit: go get github.com/gorilla/mux
199
Simple example
GormHelloWorld
200
Thank you!!!
201
http://www.golangbootcamp.com/book/collection_types#uid56
202

Contenu connexe

Tendances

C programming interview questions
C programming interview questionsC programming interview questions
C programming interview questions
adarshynl
 
C# note
C# noteC# note
Basic C Programming language
Basic C Programming languageBasic C Programming language
Basic C Programming language
Abhishek Soni
 
Oops
OopsOops
Computer programming questions
Computer programming questionsComputer programming questions
Computer programming questions
estoredesignerclothi
 
Introduction of c programming unit-ii ppt
Introduction of  c programming unit-ii pptIntroduction of  c programming unit-ii ppt
Introduction of c programming unit-ii ppt
JStalinAsstProfessor
 
OOP in C++
OOP in C++OOP in C++
OOP in C++
ppd1961
 
C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1
ReKruiTIn.com
 
C++ Langauage Training in Ambala ! BATRA COMPUTER CENTRE
C++  Langauage Training in Ambala ! BATRA COMPUTER CENTREC++  Langauage Training in Ambala ! BATRA COMPUTER CENTRE
C++ Langauage Training in Ambala ! BATRA COMPUTER CENTRE
jatin batra
 
Basics1
Basics1Basics1
Basics1
phanleson
 
Difference between java and c#
Difference between java and c#Difference between java and c#
Difference between java and c#
TECOS
 
Top C Language Interview Questions and Answer
Top C Language Interview Questions and AnswerTop C Language Interview Questions and Answer
Top C Language Interview Questions and Answer
Vineet Kumar Saini
 
C++ Interview Questions
C++ Interview QuestionsC++ Interview Questions
C++ Interview Questions
Kaushik Raghupathi
 
5 introduction-to-c
5 introduction-to-c5 introduction-to-c
5 introduction-to-c
Rohit Shrivastava
 
C# lecture 2: Literals , Variables and Data Types in C#
C# lecture 2: Literals , Variables and Data Types in C#C# lecture 2: Literals , Variables and Data Types in C#
C# lecture 2: Literals , Variables and Data Types in C#
Dr.Neeraj Kumar Pandey
 
Learn C# Programming - Decision Making & Loops
Learn C# Programming - Decision Making & LoopsLearn C# Programming - Decision Making & Loops
Learn C# Programming - Decision Making & Loops
Eng Teong Cheah
 
Chapter 2 c#
Chapter 2 c#Chapter 2 c#
Chapter 2 c#
megersaoljira
 
Features of c
Features of cFeatures of c
Features of c
Hitesh Kumar
 
C++ interview question
C++ interview questionC++ interview question
C++ interview question
Durgesh Tripathi
 

Tendances (19)

C programming interview questions
C programming interview questionsC programming interview questions
C programming interview questions
 
C# note
C# noteC# note
C# note
 
Basic C Programming language
Basic C Programming languageBasic C Programming language
Basic C Programming language
 
Oops
OopsOops
Oops
 
Computer programming questions
Computer programming questionsComputer programming questions
Computer programming questions
 
Introduction of c programming unit-ii ppt
Introduction of  c programming unit-ii pptIntroduction of  c programming unit-ii ppt
Introduction of c programming unit-ii ppt
 
OOP in C++
OOP in C++OOP in C++
OOP in C++
 
C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1
 
C++ Langauage Training in Ambala ! BATRA COMPUTER CENTRE
C++  Langauage Training in Ambala ! BATRA COMPUTER CENTREC++  Langauage Training in Ambala ! BATRA COMPUTER CENTRE
C++ Langauage Training in Ambala ! BATRA COMPUTER CENTRE
 
Basics1
Basics1Basics1
Basics1
 
Difference between java and c#
Difference between java and c#Difference between java and c#
Difference between java and c#
 
Top C Language Interview Questions and Answer
Top C Language Interview Questions and AnswerTop C Language Interview Questions and Answer
Top C Language Interview Questions and Answer
 
C++ Interview Questions
C++ Interview QuestionsC++ Interview Questions
C++ Interview Questions
 
5 introduction-to-c
5 introduction-to-c5 introduction-to-c
5 introduction-to-c
 
C# lecture 2: Literals , Variables and Data Types in C#
C# lecture 2: Literals , Variables and Data Types in C#C# lecture 2: Literals , Variables and Data Types in C#
C# lecture 2: Literals , Variables and Data Types in C#
 
Learn C# Programming - Decision Making & Loops
Learn C# Programming - Decision Making & LoopsLearn C# Programming - Decision Making & Loops
Learn C# Programming - Decision Making & Loops
 
Chapter 2 c#
Chapter 2 c#Chapter 2 c#
Chapter 2 c#
 
Features of c
Features of cFeatures of c
Features of c
 
C++ interview question
C++ interview questionC++ interview question
C++ interview question
 

Similaire à The GO programming language

Go Programming language, golang
Go Programming language, golangGo Programming language, golang
Go Programming language, golang
Basil N G
 
Escape Sequences and Variables
Escape Sequences and VariablesEscape Sequences and Variables
Escape Sequences and Variables
yarkhosh
 
Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++
Rasan Samarasinghe
 
Pc module1
Pc module1Pc module1
Pc module1
SANTOSH RATH
 
INTRODUCTION TO C PROGRAMMING in basic c language
INTRODUCTION TO C PROGRAMMING in basic c languageINTRODUCTION TO C PROGRAMMING in basic c language
INTRODUCTION TO C PROGRAMMING in basic c language
GOKULKANNANMMECLECTC
 
Golang online course
Golang online courseGolang online course
Golang online course
bestonlinecoursescoupon
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
Aiman Hud
 
Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
Sangharsh agarwal
 
#Code2 create c++ for beginners
#Code2 create  c++ for beginners #Code2 create  c++ for beginners
#Code2 create c++ for beginners
GDGKuwaitGoogleDevel
 
(2) cpp imperative programming
(2) cpp imperative programming(2) cpp imperative programming
(2) cpp imperative programming
Nico Ludwig
 
Unit ii
Unit   iiUnit   ii
Unit ii
sathisaran
 
Looping and switch cases
Looping and switch casesLooping and switch cases
Looping and switch cases
MeoRamos
 
Data Type in C Programming
Data Type in C ProgrammingData Type in C Programming
Data Type in C Programming
Qazi Shahzad Ali
 
Advanced C
Advanced C Advanced C
Introduction to c
Introduction to cIntroduction to c
Introduction to c
Ajeet Kumar
 
(6) c sharp introduction_advanced_features_part_i
(6) c sharp introduction_advanced_features_part_i(6) c sharp introduction_advanced_features_part_i
(6) c sharp introduction_advanced_features_part_i
Nico Ludwig
 
INTRODUCTION TO CODING-CLASS VI LEVEL-DESCRIPTION ABOUT SYNTAX LANGUAGE
INTRODUCTION TO CODING-CLASS VI LEVEL-DESCRIPTION ABOUT SYNTAX LANGUAGEINTRODUCTION TO CODING-CLASS VI LEVEL-DESCRIPTION ABOUT SYNTAX LANGUAGE
INTRODUCTION TO CODING-CLASS VI LEVEL-DESCRIPTION ABOUT SYNTAX LANGUAGE
RathnaM16
 
classVI_Coding_Teacher_Presentation.pptx
classVI_Coding_Teacher_Presentation.pptxclassVI_Coding_Teacher_Presentation.pptx
classVI_Coding_Teacher_Presentation.pptx
MaaReddySanjiv
 
classVI_Coding_Teacher_Presentation.pptx
classVI_Coding_Teacher_Presentation.pptxclassVI_Coding_Teacher_Presentation.pptx
classVI_Coding_Teacher_Presentation.pptx
ssusere336f4
 
venkatesh.pptx
venkatesh.pptxvenkatesh.pptx
venkatesh.pptx
KishoreRedla
 

Similaire à The GO programming language (20)

Go Programming language, golang
Go Programming language, golangGo Programming language, golang
Go Programming language, golang
 
Escape Sequences and Variables
Escape Sequences and VariablesEscape Sequences and Variables
Escape Sequences and Variables
 
Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++
 
Pc module1
Pc module1Pc module1
Pc module1
 
INTRODUCTION TO C PROGRAMMING in basic c language
INTRODUCTION TO C PROGRAMMING in basic c languageINTRODUCTION TO C PROGRAMMING in basic c language
INTRODUCTION TO C PROGRAMMING in basic c language
 
Golang online course
Golang online courseGolang online course
Golang online course
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
 
#Code2 create c++ for beginners
#Code2 create  c++ for beginners #Code2 create  c++ for beginners
#Code2 create c++ for beginners
 
(2) cpp imperative programming
(2) cpp imperative programming(2) cpp imperative programming
(2) cpp imperative programming
 
Unit ii
Unit   iiUnit   ii
Unit ii
 
Looping and switch cases
Looping and switch casesLooping and switch cases
Looping and switch cases
 
Data Type in C Programming
Data Type in C ProgrammingData Type in C Programming
Data Type in C Programming
 
Advanced C
Advanced C Advanced C
Advanced C
 
Introduction to c
Introduction to cIntroduction to c
Introduction to c
 
(6) c sharp introduction_advanced_features_part_i
(6) c sharp introduction_advanced_features_part_i(6) c sharp introduction_advanced_features_part_i
(6) c sharp introduction_advanced_features_part_i
 
INTRODUCTION TO CODING-CLASS VI LEVEL-DESCRIPTION ABOUT SYNTAX LANGUAGE
INTRODUCTION TO CODING-CLASS VI LEVEL-DESCRIPTION ABOUT SYNTAX LANGUAGEINTRODUCTION TO CODING-CLASS VI LEVEL-DESCRIPTION ABOUT SYNTAX LANGUAGE
INTRODUCTION TO CODING-CLASS VI LEVEL-DESCRIPTION ABOUT SYNTAX LANGUAGE
 
classVI_Coding_Teacher_Presentation.pptx
classVI_Coding_Teacher_Presentation.pptxclassVI_Coding_Teacher_Presentation.pptx
classVI_Coding_Teacher_Presentation.pptx
 
classVI_Coding_Teacher_Presentation.pptx
classVI_Coding_Teacher_Presentation.pptxclassVI_Coding_Teacher_Presentation.pptx
classVI_Coding_Teacher_Presentation.pptx
 
venkatesh.pptx
venkatesh.pptxvenkatesh.pptx
venkatesh.pptx
 

Dernier

The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
kalichargn70th171
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
Philip Schwarz
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
Bert Jan Schrijver
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
ICS
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
Grant Fritchey
 
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
Green Software Development
 
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
mz5nrf0n
 
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
kalichargn70th171
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
Rakesh Kumar R
 
Lecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptxLecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptx
TaghreedAltamimi
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
rodomar2
 
Malibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed RoundMalibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed Round
sjcobrien
 
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
safelyiotech
 
YAML crash COURSE how to write yaml file for adding configuring details
YAML crash COURSE how to write yaml file for adding configuring detailsYAML crash COURSE how to write yaml file for adding configuring details
YAML crash COURSE how to write yaml file for adding configuring details
NishanthaBulumulla1
 
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Julian Hyde
 
Liberarsi dai framework con i Web Component.pptx
Liberarsi dai framework con i Web Component.pptxLiberarsi dai framework con i Web Component.pptx
Liberarsi dai framework con i Web Component.pptx
Massimo Artizzu
 
E-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet DynamicsE-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet Dynamics
Hornet Dynamics
 
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdfTop Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
VALiNTRY360
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
Green Software Development
 

Dernier (20)

The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
 
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
 
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
 
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
 
Lecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptxLecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptx
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
 
Malibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed RoundMalibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed Round
 
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
 
YAML crash COURSE how to write yaml file for adding configuring details
YAML crash COURSE how to write yaml file for adding configuring detailsYAML crash COURSE how to write yaml file for adding configuring details
YAML crash COURSE how to write yaml file for adding configuring details
 
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)
 
Liberarsi dai framework con i Web Component.pptx
Liberarsi dai framework con i Web Component.pptxLiberarsi dai framework con i Web Component.pptx
Liberarsi dai framework con i Web Component.pptx
 
E-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet DynamicsE-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet Dynamics
 
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdfTop Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
 

The GO programming language

  • 1. Marco Sabatini Senior Software Engineer sabatini.m@gmail.com https://it.linkedin.com/in/sabatinimarco Contacts 1
  • 2. The GO Programming Language 2
  • 3. Agenda Agenda 1° Day • Overview • Variable types overview and scope • Environment setup • Packages • Exercises Agenda 3° Day • Concurrent programming • File Handling • Linking C shared libs • Exercises Agenda 2° Day • Pointers • Collections • Procedural programming • Struct • Interfaces • Exercises 3 Agenda 4°Day • Gorilla web toolkit • Gorm • Exercises
  • 4. Agenda 1° Day Agenda • Overview • Variable types overview and scope • Environment setup • Packages • Exercises 4
  • 5. Overview (authors) • Go, also commonly referred to as golang, is a programming language initially developed at Google in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson. • It is a statically-typed language with syntax loosely derived from that of C, adding garbage collection, type safety, some dynamic-typing capabilities, additional built-in types such as variable-length arrays and key-value maps, and a large standard library. •Go programs are “compiled” rather than interpreted so as to have the best possible performance. 5
  • 6. Overview (Google has big problems) Go is a programming language designed by Google to help solve Google’s problems. What problems? • C++ for servers, plus lots of Java and Python • thousand of engineers • gazillions of lines of code • distributed build system • gazillions of machines, which are treated as a modest number of compute clusters 6
  • 7. Overview (The reason of go) Goals: • eliminate slowness • eliminate clumsiness • improve effectiveness • maintain (even improve) scale Go was designed by and for people who write – read – debug – maintain, large software systems. Go’s purpose is not research programming language design. Go’s purpose is to make its designers’ programming lives better. 7
  • 9. Overview (project status from Google) •Go became a public open source project on November 10, 2009. After a couple of years of very active design and development, stability was called for and Go 1 was released on March 28, 2012. Go 1, which includes a language specification, standard libraries, and custom tools, provides a stable foundation for creating reliable products, projects, and publications. •With that stability established, we are using Go to develop programs, products, and tools rather than actively changing the language and libraries. In fact, the purpose of Go 1 is to provide long-term stability. Backwards-incompatible changes will not be made to any Go 1 point release. We want to use what we have to learn how a future version of Go might look, rather than to play with the language underfoot •Of course, development will continue on Go itself, but the focus will be on performance, reliability, portability and the addition of new functionality such as improved support for internationalization. 9
  • 10. Overview (important stuff) • Object oriented without inheritance • Syntax sugar declaration • Strong and Static types • Interfaces, but no declaration (duck typing) • Functions and Methods (with receivers) • Visibility with the first letter of symbol • No exceptions (error interface) • Unused imports and variables occurs compile error • Excellent and complete standard library 10
  • 11. Overview (go is a tool) 11
  • 13. Overview (let’s start coding…) // hello.go package main import ( ➊ "fmt" "os" "strings" ) func main() { who := "World!" ➋ if len(os.Args) > 1 { /* os.Args[0] is "hello" or "hello.exe" */ ➌ who = strings.Join(os.Args[1:], " ") ➍ } fmt.Println("Hello", who) ➎ } Go uses C++-style comments: // for single-line comments that finish at the end of the line and /* ... */ for comments that can span multiple lines. Every piece of Go code exists inside a package, and every Go program must have a main package with a main() function which serves as the program’s entry point, that is, the function that is executed first. The import statement (➊) imports three packages from the standard library. The first statement in the main() function (➋; using the := operator) is called a short variable declaration in Go terminology. The os.Args variable is a slice of strings (➌). If the user has entered one or more command line arguments the if condition is satisfied and we set the who string to contain all the arguments joined up as a single string (➍). Finally, in the last statement (➎), we print Hello, a space, the string held in the who variable, and a newline. 13
  • 14. Syntax overview 1/2 • Basically C-like with reversed types and declarations, plus keywords to introduce each type of declaration. • Basic control structures are familiar: • Note: no parentheses, but braces required. 14
  • 15. Syntax overview 2/2 Semicolons terminate statements but: • lexer inserts them automatically at end of line if the previous token could end a statement. • Note: much cleaner, simpler than JavaScript rule! Thus no semis needed in this program: In practice, Go code almost never has semicolons outside for and if clauses 15
  • 16. Declaration Declarations are introduced by a keyword (var, const, type, func) and are reversed compared to C: Why are they reversed? Earlier example: • Both p and q have type *int. • Also functions read better and are consistent with other declarations. 16
  • 17. Var Identifier • Variable declarations are introduced by “var” identifier. • They may have a type or an initialization expression; • One or both must be present. • Initializers must match variables (and types!). 17
  • 18. Distributing Var Annoying to type var all the time. Group with parens: Applies to const, type, var but not func!!! 18
  • 19. The := “short declaration” Within functions (only), declarations of the form: can be shortened to: (Another reason for the name/type reversal.) The type is that of the value (for ideal numbers, get int or float64 or complex128, accordingly.) These are used a lot and are available in places such as for loop initializers. 19
  • 20. Const • Constant declarations are introduced by const. • They must have a "constant expression", evaluated at compile time, as initialiser and may have an optional type specifier. 20
  • 21. Iota Constant declarations can use the counter iota, which starts at 0 in each const block and increments at each implicit semicolon (end of line). Shorthand: Previous type and expressions repeat. 21
  • 22. Type Type declarations are introduced by type. We'll learn more about types later but here are some examples: 22
  • 23. New The built-in function new allocates memory. Syntax is like a function call, with type as argument, similar to C++. Returns a pointer to the allocated object (pointers ) Later we'll see how to build slices and such. There is no delete or free; Go has garbage collection. 23
  • 24. Assignment Assignment is easy and familiar: But multiple assignment works too: Functions can return multiple values (details later): 24
  • 25. If Basic form is familiar, but no dangling else problem: Initialization statement allowed; requires semicolon. Useful with multivariate functions: Missing condition means true, which is not too useful in this context but handy in for, switch. 25
  • 26. For Basic form is familiar: Missing condition means true: But you can leave out the semis too: Don't forget multivariate assigments: 26
  • 27. Switch 1/2 Switches are somewhat similar to C's. But there are important syntactic and semantic differences:
 - expressions need not be constant or even int. - no automatic fall through
 - instead, lexically last statement can be fall-through - multiple cases can be comma-separated 27
  • 28. Switch 2/2 Go's switch is more powerful than C's. Familiar form: The expressions can be any type and a missing switch expression means true. Result: if-else chain: or 28
  • 29. Break and continue … The break and continue statements work as in C. They may specify a label to affect an outer structure: 29
  • 30. Agenda 1° Day Agenda • Overview • Variable types overview and scope • Environment setup • packages • Exercises 30
  • 31. Go Typing • Go is a statically typed programming language. This means that variables always have a specific type and that type cannot change. • Static typing may seem cumbersome at first. You'll spend a large amount of your time just trying to fix your program so that it finally compiles. But types help us reason about what our program is doing and catch a wide variety of common mistakes. • Go comes with several built-in data types which we will now look at in more detail. 31
  • 32. Numeric 1/3 A. Generally we split numbers into two different kinds: integers and floating-point numbers. • Go's integer types are: uint8, uint16, uint32, uint64, int8, int16, int32 and int64. 8, 16, 32 and 64 tell us how many bits each of the types use. • In addition there two alias types: byte which is the same as uint8 and rune which is the same as int32. • There are also 3 machine dependent integer types: uint, int and uintptr. They are machine dependent because their size depends on the type of architecture you are using. 32
  • 33. Numeric 2/3 • Floating point numbers are numbers that contain a decimal component (real numbers). (1.234, 123.4, 0.00001234, 12340000) • Like integers floating point numbers have a certain size (32 bit or 64 bit). Using a larger sized floating point number increases it's precision. (how many digits it can represent) • In addition to numbers there are several other values which can be represented: “not a number” (NaN, for things like 0/0) and positive and negative infinity. (+∞ and −∞) • Go has two floating point types: float32 and float64 • Additional types for representing complex numbers (numbers with imaginary parts): complex64 and complex128 33
  • 35. String 1/2 • Go strings are made up of individual bytes, usually one for each character. (Characters from other languages like Chinese are represented by more than one byte) • String literals can be created using double quotes "Hello World" or back ticks `Hello World`. • Common operations: • len(“Hello World!!!”) • “Hello World”[1] (access individual char) • “Hello ”+”World!!!” (string concatenation) • Examples!!! 35
  • 36. String 2/2 String memory organization 36
  • 37. Boolean A boolean value (named after George Boole) is a special 1 bit integer type used to represent true and false (or on and off). Three logical operators are used with boolean values: 37
  • 38. Agenda 1° Day Agenda • Overview • Variable types overview and scope • Environment setup • packages • Exercises 38
  • 39. Golang Setting programming environment 1/2 Compiler&Runtime • https://golang.org/doc/install (package download web pages) • export GOPATH=$HOME/go (environment variable to store GO base path) • export PATH=$PATH:$GOPATH/bin (add “GO” runtime binary to path) 39
  • 40. Golang Setting programming environment 2/2 IDE • GoClipse is an Eclipse IDE for the Go programming language. The purpose of GoClipse is to create an environment in which development of Go is easy for a beginner to intermediate user. • https://goclipse.github.io ( documentation and download link ) • Code completion ( setting GOPATH ) • Source navigation • Compilation • Execution (Run As) • Debugging (Debug As) 40
  • 41. Agenda 1° Day Agenda • Overview • Variable types overview and scope • Environment setup • Packages • Exercises 41
  • 42. Golang source code project structure Go code must be kept inside a workspace. A workspace is a directory hierarchy with three directories at its root: • root_project • src • bin • pkg then you have to export this env variables: export GOROOT=/usr/local/go export GOPATH=~/workspace/me/go export PATH=$PATH:$GOROOT/bin:$GOPATH/bin build: “go install” 42
  • 43. Golang packages&docs Packages only really make sense in the context of a separate program which uses them. • Execute “go install” creates average.a linkable object file. • Can reuse your code Example of documentation: godoc average_kg godoc -http:”6060” Golang has a large number of precompiled packages we can use in our software!!! 43
  • 44. Testing code • simple_test_example: go test simple_test_example • bench_test_example: go test bench_test_example 44
  • 45. Agenda 1° Day Agenda • Overview • Variable types overview and scope • Environment setup • packages • Exercises 45
  • 46. Exercises 1. reverse a string ascii and utf8 2. packaging reverse string ascii&utf8 func 3. pattern match (find email in a text) 4. packaging pattern match email func 5. pass values from CLI to previous exercises (args) 6. pass values from CLI to previous exercises (flags pkg) 7. fmt.Scanf (read doc and use it) 8. remove duplicates char in a string 46
  • 47. Agenda 2° Day Agenda • Pointers • Collections • Procedural programming • Struct • Interfaces • Exercises 47
  • 48. Pointers Overview 1/2 When we call a function that takes an argument, that argument is copied to the function: In this program the zero function will not modify the original x variable in the main function. But what if we wanted to? One way to do this is to use a special data type known as a pointer 48
  • 49. Pointers Overview 2/2 Pointers reference a location in memory where a value is stored rather than the value itself. (They point to something else) By using a pointer (*int) the zero function is able to modify the original variable. 49
  • 50. ‘*’ and ‘&’ operators 1/2 1. In Go a pointer is represented using the * (asterisk) character followed by the type of the stored value. 2. ‘*’ is also used to “dereference” pointer variables. Dereferencing a pointer gives us access to the value the pointer points to. 3. *xPtr = 0 we are saying “store the int 0 in the memory location xPtr refers to”. 4. xPtr = 0 instead we will get a compiler error because xPtr is not an int it's a *int, which can only be given another *int. 50
  • 51. ‘*’ and ‘&’ operators 1/2 We use the ‘&’ operator to find the address of a variable. &i returns a *int (pointer to an int) because i is an int. This is what allows us to modify the original variable. &i and ptr are the same memory location. 51
  • 52. The New function Another way to get a pointer is to use the built-in new function: In some programming languages there is a significant difference between using new and &, with great care being needed to eventually delete anything created with new. Go is not like this, it's a garbage collected programming language which means memory is cleaned up automatically when nothing refers to it anymore. new takes a type as an argument, allocates enough memory to fit a value of that type and returns a pointer to it. 52
  • 53. Garbage Collector Go 1 > 1.4 has used a parallel stop-the-world (STW) collector. While STW collection has many downsides, it does at least have predictable and controllable heap growth behavior. The sole tuning knob for the STW collector was “GOGC”, the relative heap growth between collections. The default setting, 100%, triggered garbage collection every time the heap size doubled over the live heap size as of the previous collection Go 1.5 will introduce a concurrent collector. 53
  • 54. Agenda 2° Day Agenda • Pointers • Collections • Procedural programming • Struct • Interfaces • Exercises 54
  • 55. Arrays An array is a numbered sequence of elements of a single type with a fixed length. In Go they look like this: declares “ar” to be an array of 3 integers, initially all set to zero. Size is part of the type. Built-in function len reports size: 55
  • 56. Arrays literals All the composite types have similar syntax for creating values. For arrays it look like this: Array of 3 integers: Array of 10 integers, first three not zero: Don't want to initialize them all? Use key:value pairs: 56
  • 57. Arrays are values Arrays are values, not implicit pointers as in C. You can take an array's address, yielding a pointer to the array (to pass it efficiently to a function): Output 57
  • 58. Pointers to arrays literals You can take the address of an array literal to get a pointer to a newly created instance: Output 58
  • 59. Slices • A slice is a reference to a section of an array. • Slices are used much more often than plain arrays. • A slice is very cheap. (More about this soon.) • A slice type looks like an array type without a size: Built-in len(a) returns the number of elements. Create a slice by "slicing" an array or slice: Valid indexes of a will then be 0 and 1; len(a)==2. 59
  • 60. Slice shorthands When slicing, first index defaults to 0: ar[:n] means the same as ar[0:n]. Second index defaults to len(array/slice): ar[n:] means the same as ar[n:len(ar)]. Thus to create a slice from an array: ar[:] means the same as ar[0:len(ar)]. 60
  • 61. A slices references an array Conceptually 61
  • 62. Making Slices Slice literals look like array literals without a size: What this does is create an array of length 5 and then create a slice to refer to it. We can also allocate a slice (and underlying array) with the built-in function make: • Why make not new? Because we need to make a slice, not just allocate the memory. • Note make([]int, 10) returns []int while new([]int) returns *[]int. • Use make to create slices, maps, and channels. 62
  • 63. Slices capacity A slice refers to an underlying array, so there may be elements off the end of the slice that are present in the array. The built-in function cap (capacity) reports how long the slice could possibly grow after. len(a) is 2 and cap(a) is 5. We can "reslice": len(a) is now 4 but cap(a) is still 5. 63
  • 64. Resizing Slices Slices can be used like growable arrays. Allocate one using make with two numbers - length and capacity - and reslice as it grows: Thus sl's length is always the number of elements, but it grows as needed. This style is cheap and idiomatic in Go!!! 64
  • 65. Slices are cheap • Feel free to resize slices as required. They are cheap to pass around; no need to allocate. • Remember they are references, so underlying storage can be modified. • For instance, I/O uses slices, not counts: Split a buffer: Strings can be sliced too, with similar efficiency. 65
  • 66. Slice functions append() Go includes two built-in functions to assist with slices: append and copy. Here is an example of append: After running this program slice1 has [1,2,3] and slice2 has [1,2,3,4,5]. append creates a new slice by taking an existing slice (the first argument) and appending all the following arguments to it. 66
  • 67. Here is an example of copy: After running this program slice1 has [1,2,3] and slice2 has [1,2]. The contents of slice1 are copied into slice2, but since slice2 has room for only two elements only the first two elements of slice1 are copied. Slice functions copy() 67
  • 68. Maps Maps are another reference type. They are declared like this: This declares a map indexed with key type string and value type float64. It is analogous to the C++ type *map<string,float64> (note the *). Given a map m, len(m) returns the number of keys. 68
  • 69. Map creation As with a slice, a map variable refers to nothing; you must put something in it before it can be used. Three ways: 1) Literal: list of colon-separated key:value pairs 2) Creation 3) Assignment 69
  • 70. Indexing Map Next few examples all use: Access an element as a value; if not present, get zero value for the map's value type: Set an element (setting twice updates value for key) 70
  • 71. Testing existence To test if a key is present in the map, we can use a multi- value assignment, the "comma ok" form: or idiomatically: If x is present in the map, sets the boolean to true and the value to the entry for the key. If not, sets the boolean to false and the value to the zero for its type. 71
  • 72. Deleting Deleting an entry in the map is a multi-variate assignment to the map entry: If keep is true, assigns v to the map; if keep is false, deletes the entry for key x. So to delete an entry: delete(m, x ) 72
  • 73. For and range (Arrays, Slices, Maps) The for loop has a special syntax for iterating over arrays, slices, maps (and more, as we'll see tomorrow). With only one variable in the range, get the key: Variables can be assigned or declared using ‘:=‘ . For arrays and slices, get index and value. 73
  • 74. Range Over String A for using range on a string loops over Unicode code points, not bytes. (Use []byte for bytes, or use a standard for). The string is assumed to contain UTF-8. If erroneous UTF-8 is encountered, the character is set to U+FFFD and the index advances by one byte. 74
  • 75. Agenda 2° Day Agenda • Pointers • Collections • Procedural programming • Struct • Interfaces • Exercises 75
  • 76. Functions A function is an independent section of code that maps zero or more input parameters to zero or more output parameters. Functions (also known as procedures or subroutines) are often represented as a black box: (the black box represents the function) We will now begin writing programs that use more than one function. 76
  • 77. Your second function This program computes the average of a series of numbers. Finding the average like this is a very general problem, so its an ideal candidate for definition as a function. The average function will need to take in a slice of float64s and return one float64. Insert this before the main function: 77
  • 78. Functions (variable scope) Functions don't have access to anything in the calling function. ok okWrong 78
  • 79. Functions (call stack) Call Stack Each time we call a function we push it onto the call stack and each time we return from a function we pop the last function off of the stack. 79
  • 80. Returning multiple values Go is also capable of returning multiple values from a function Three changes are necessary: A. change the return type to contain multiple types separated by , B. change the expression after the return so that it contains multiple expressions separated by , C. change the assignment statement so that multiple values are on the left side of the := or =. Multiple values are often used to return an error value along with the result (x, err := f()), or a boolean to indicate success (x, ok := f()). 80
  • 81. Variadic functions • By using “…" before the type name of the last parameter you can indicate that it takes zero or more of those parameters. • In this case we take zero or more ints. • We invoke the function like any other function except we can pass as many ints as we want. This is precisely how the fmt.Println function is implemented: 81
  • 82. Closure 1/2 It is possible to create functions inside of functions: add is a local variable that has the type func(int, int) int (a function that takes two ints and returns an int). When you create a local function like this it also has access to other local variables. A function like this together with the non-local vari- ables it references is known as a closure. In this case increment and the variable x form the closure. 82
  • 83. Closure 2/2 It is possible to create functions inside of functions: • One way to use closure is by writing a function which returns another function. • makeEvenGenerator returns a function which generates even numbers. Each time it's called it adds 2 to the local i variable which. 83
  • 84. Recursion Finally a function is able to call itself No Factorial example please!!! Some hacking on Go source code (path.go) !!! 84
  • 85. Defer Go has a special statement called defer which schedules a function call to be run after the function completes defer is often used when resources need to be freed in some way. For example when we open a file we need to make sure to close it later. This has 3 advantages: (1) it keeps our Close call near our Open call so its easier to understand, (2) if our function had multiple return statements (perhaps one in an if and one in an else) Close will happen before both of them and (3) deferred functions are run even if a run-time panic occurs. 85
  • 86. Panic & Recover We can handle a run-time panic with the built-in recover function. Recover stops the panic and returns the value that was passed to the call to panic. A panic generally indicates a programmer error (for example attempting to access an index of an array that's out of bounds, forgetting to initialize a map, etc.) Error Ok 86
  • 87. Memoization If a pure function is expensive to compute and frequently used with the same arguments, we can use memoization to reduce the processing overhead The memoization technique is where we store the results of a computation so that when the same computation is next requested we are able to return the stored results rather than perform the computation all over again 87
  • 88. Higher order function A higher order function is a function that takes one or more other functions as arguments and uses them in its own body. Output? 88
  • 89. Agenda 2° Day Agenda • Pointers • Collections • Procedural programming • Structs • Interfaces • Exercises 89
  • 90. Structs Structs should feel very familiar: simple declarations of data fields. More usual: Structs allow the programmer to define the layout of memory. 90
  • 91. Structs are values Structs are values and new(StructType) returns a pointer to a zero value (memory all zeros). There is no -> notation for structure pointers. Go provides the indirection for you. 91
  • 92. Making structs Structs are values so you can make a zeroed one just by declaring it. You can also allocate one with new. Struct literals have the expected syntax As with arrays, taking the address of a struct literal gives the address of a newly created value.These examples are constructors. 92
  • 93. Exporting types and fields The fields (and methods, coming up soon) of a struct must start with an Uppercase letter to be visible outside the package. Private type and fields: Exported type and fields: Exported type with mix of fields: You may even have a private type with exported fields. Exercise: when is that useful? 93
  • 94. Anonymous fields • Inside a struct, you can declare fields, such as another struct, without giving a name for the field. • These are called anonymous fields and they act as if the inner struct is simply inserted or "embedded" into the outer. • This simple mechanism provides a way to derive some or all of your implementation from another type or types. An example follows!!! 94
  • 95. An anonymous struct field B acts as if it has four fields, ax, ay, bx, and by. It's almost as if B is {ax, ay int; bx, by float64}. However, literals for B must be filled out in detail: Prints: 1, 2, 3, 4 95
  • 96. Anonymous fields have type as name But it's richer than simple interpolation of the fields: B also has a field A. The anonymous field looks like a field whose name is its type. Prints {1 2}. If A came from another package,the field is called A: 96
  • 97. Anonymous fields of any type Any named type, or pointer to one, may be used in an anonymous field and it may appear at any location in the struct. Prints 3.5 7 hello 97
  • 98. Conflicts and hiding If there are two fields with the same name (possibly a type-derived name), these rules apply: 1) An outer name hides an inner name.
 This provides a way to override a field/method. 2) If the same name appears twice at the same level, it is an error if the name is used by the program. (If it's not used, it doesn't matter.) No rules to resolve the ambiguity; it must be fixed. 98
  • 99. Conflict examples Using c.a is an error: is it c.A.a or c.B.a? Using d.b is OK: it's the float64, not d.B.b Can get at the inner b by D.B.b. 99
  • 100. Methods on struct pointers • Go has no classes, but you can attach methods to any type. • The methods are declared, separate from the type declaration, as functions with an explicit receiver (like java this). • The obvious struct case: Note: explicit receiver (no automatic this), in this case of type *Point, used within the method. 100
  • 101. Methods on struct values A method does not require a pointer as a receiver. This is a bit expensive, because the Point3 will always be passed to the method by value, but it is valid Go. 101
  • 102. Invoking a methods Just as you expect. A non-struct example: 102
  • 103. Ground rules for methods • Methods are attached to a named type, say Foo, and are statically bound. • The type of a receiver in a method can be either *Foo or Foo. You can have some Foo methods and some *Foo methods. • Foo itself cannot be a pointer type, although the methods can have receiver type *Foo. • The type Foo must be defined in the same package as all its methods. 103
  • 104. Pointers & Values Go automatically indirects/dereferences values for you when invoking methods. For instance, even though a method has receiver type *Point you can invoke it on an addressable value of type Point. Similarly, if methods are on Point3 you can use a value of type *Point3: 104
  • 105. Methods on anonymous fields Naturally, when an anonymous field is embedded in a struct, the methods of that type are embedded as well - in effect, it inherits the methods. This mechanism offers a simple way to emulate some of the effects of subclassing and inheritance. 105
  • 107. Overriding a method Overriding works just as with fields. Of course you can have multiple anonymous fields with various types - a simple version of multiple inheritance. The conflict resolution rules keep things simple, though. 107
  • 108. Another example A more compelling use of an anonymous field. Note that Lock's receiver is (the address of) the Mutex field, not the surrounding structure. (Contrast to subclassing) 108
  • 109. Other types 1/3 Methods are not just for structs. They can be defined for any (non-pointer) type. The type must be defined in your package though. You can't write a method for int but you can declare a new int type and give it methods. 109
  • 110. Other types 2/3 Now we have an enumeration-like type that knows how to print itself. 110
  • 111. Other types 3/3 By techniques to be divulged soon, fmt.Print and friends can identify values that implement the method. String as we defined for type Day. Such values are automatically formatted by invoking the method. Thus: prints 0 Monday 1 Tuesday. Println can tell a plain 0 from a 0 of type Day. So define a String method for your types and they will print nicely with no more work. 111
  • 112. Fileds and methods visibility Go is very different from C++ in the area of visibility. Go's rules: 1) Go has package scope (C++ has file scope). 2) ︎Spelling determines exported/local (pub/priv). 3)︎Structs in the same package have full access to one another's fields and methods. 4) Local type can export its fields and methods.
 5) No true subclassing, so no notion of "protected". These simple rules seem to work well in practice. 112
  • 113. Agenda 2° Day Agenda • Pointers • Collections • Procedural programming • Structs • Interfaces • Exercises 113
  • 114. Interfaces Overview • So far, all the types we have examined have been concrete: they implement something. • There is one more type to consider: the interface type. • It is completely abstract; it implements nothing. Instead, it specifies a set of properties an implementation must provide. • Interface as a concept is very close to that of Java, and Java has an interface type, but the "interface value" concept of Go is novel. 114
  • 115. Interfaces definition The word "interface" is a bit overloaded in Go: 1. There is the concept of an interface 2. There is an interface type 3. There are values of that type. Definition: An interface is a set of methods. To turn it around, the methods implemented by a concrete type such as a struct form the interface of that type. 115
  • 116. Example We saw this simple type before: The interface of type Point has the method: It's not because the interface abstracts away the receiver. We embedded Point in a new type, NamedPoint; NamedPoint has the same interface. 116
  • 117. The interface type An interface type is a specification of an interface, a set of methods implemented by some other types. Here's a simple one, with only one method: This is a definition of the interface implemented by Point, or in our terminology, Point implements Abs Interface Also, NamedPoint and Point3 implement Abs Interface Methods are written inside the interface declaration. 117
  • 118. Example MyFloat implements AbsInterface even though float64 does not. (Aside: MyFloat is not a "boxing" of float64; its representation is identical to float64.) 118
  • 119. Interface embedding Interfaces can embed other interfaces and the effect is al- most the same as if we had written the embedded interface’s method signatures in the interface that embeds it 119
  • 120. Interface value Once a variable is declared with interface type, it may store any value that implements that interface. 120
  • 121. In memory ai is not a pointer! It's a multiword data structure. At different times it has different value and type: 121
  • 122. Summary 1) Interfaces define sets of methods. They are pure and abstract: no implementation, no data fields. Go has a clear separation between interface and implementation. 2) Interface values are just that: values. They contain any concrete value that implements all the methods defined in the interface. That concrete value may or may not be a pointer. 3) Types implement interfaces just by having methods. They do not have to declare that they do so. For instance, every type implements the empty interface, interface{}. 122
  • 123. Example io.Writer Here is the actual signature of fmt.Fprintf: It doesn't write to a file, it writes to something of type io.Writer, that is, Writer defined in the io package: Fprintf can therefore be used to write to any type that has a canonical Write method, including files, pipes, network connections, and... 123
  • 124. Example Buffered I/O ... a write buffer. This is from the bufio package: bufio.Writer implements the canonical Write method. It also has a factory: give it an io.Writer, it will return a buffered io.Writer in the form of a bufio.Writer: And of course, os.File implements Writer too. 124
  • 125. Putting it together Buffering works for anything that Writes. Feels almost like Unix pipes, doesn't it? The composability is powerful; see crypto packages. 125
  • 126. Other public interfaces in io The io package has: Reader Writer ReadWriter ReadWriteCloser These are stylized interfaces but obvious: they capture the functionality of anything implementing the functions listed in their names. This is why we can have a buffered I/O package with an implementation separate from the I/O itself: it both accepts and provides interface values. 126
  • 127. Comparison In C++ terms, an interface type is like a pure abstract class, specifying the methods but implementing none of them. In Java terms, an interface type is much like a Java interface. However, in Go there is a major difference:
 A type does not need to declare the interfaces it implements, nor does it need to inherit from an interface type. If it has the methods, it implements the interface. 127
  • 128. Anonymous fields work too LockedBufferedWriter implements io.Writer, but also, through the anonymous Mutex, 128
  • 129. HTTP service example This is the interface defined by the HTTP server package. To serve HTTP, define a type that implements this interface and connect it to the server (details omitted). 129
  • 130. A function that serves HTTP Now we define a type to implement ServeHTTP: Convert function to attach method, implement the interface: 130
  • 131. Containers & the empty interface Sketch of the implementation of vectors. (In practice, tend to use raw slices instead, but this is informative): Vectors can contain anything because any type implements the empty interface. (In fact every element could be of different type.) 131
  • 132. Type assertions Once you put something into a Vector, it's stored as an interface value. Need to "unbox" it to get the original back: use a "type assertion". Syntax: Will fail if type is wrong - but see next slide. Type assertions always execute at run time. Compiler rejects assertions guaranteed to fail. 132
  • 133. Interface to interface conversion So far we've only moved regular values into and out of interface values, but interface values that contain the appropriate methods can also be converted. In effect, it's the same as unboxing the interface value to extract the underlying concrete value, then boxing it again for the new interface type. The conversion's success depends on the underlying value, not the original interface type. 133
  • 134. Interface to interface example Given: These are all OK: 134
  • 135. Testing with type assertions Can use "comma ok" type assertions to test a value for type. 135
  • 136. Testing with a type switch Special syntax: 136
  • 137. Does v implement m()? Going one step further, can test whether a value implements a method. This is how Print etc. check if type can print itself. 137
  • 138. Reflection and … There is a reflection package (reflect) that builds on these ideas to let you examine values to discover their type. Too intricate to describe here but Printf etc. use it to analyze the its arguments. Inside Printf, the args variable becomes a slice of the specified type, i.e. []interface{}, and Printf uses the reflection package to unpack each element to analyze its type. 138
  • 139. Reflection and Print As a result, Printf and its friends know the actual types of their arguments. Because they know if the argument is unsigned or long, there is no %u or %ld, only %d. This is also how Print and Println can print the arguments nicely without a format string. There is also a %v ("value") format that gives default nice output from Printf for values of any type. Prints -1 hello [1 2 3] 456.
 In fact, %v is identical to the formatting done by Print and Println 139
  • 140. Agenda 2° Day Agenda • Pointers • Collections • Procedural programming • Structs • Interfaces • Exercises 140
  • 141. Exercise 1. swap var 2. sort int array 3. sort string array 4. make append function for slice 5. circular linked list 6. stack 141
  • 142. Agenda 3° Day Agenda • Concurrent programming • File Handling • Linking C shared libs • Exercises 142
  • 143. Goroutines Terminology: There are many terms for "things that run concurrently" - process, thread, POSIX thread, NPTL thread, lightweight process, ..., but these all mean slightly different things. None means exactly how Go does concurrency. So we introduce a new term: goroutine. 143
  • 144. Definition A goroutine is a Go function or method executing concurrently in the same address space as other goroutines. A running program consists of one or more goroutines. It's not the same as a thread, process, etc. It's a goroutine. Note: Concurrency and parallelism are different concepts. Look them up if you don't understand the difference. 144
  • 145. Starting a goroutine Invoke a function or method and say go: Prints??? 145
  • 146. Some simple facts Goroutines are cheap. Goroutines exit by returning from their top-level function, or just falling off the end. Goroutines can run concurrently on different processors, sharing memory. You don't have to worry about stack size. 146
  • 147. Stacks In gccgo, at least for now, goroutines are pthreads. In 6g they're multiplexed onto threads, so they are much cheaper. In both worlds, stacks are small (a few kB) and grow as needed. Thus goroutines use little memory, you can have lots of them, and they can dynamically have huge stacks. The programmer shouldn't have to think about the stack size issue, and in Go, it doesn't even come up. 147
  • 148. Scheduling Goroutines are multiplexed as needed onto system threads. When a goroutine executes a blocking system call, no other goroutine is blocked. Plan to do the same for CPU-bound goroutines at some point, but for now, if you want user - level parallelism in 6g* you must set shell var: GOMAXPROCS or call runtime.GOMAXPROCS(n). GOMAXPROCS tells the runtime scheduler how many user- space-executing goroutines to run at once, ideally on different CPU cores. *gccgo always uses one thread per goroutine. 148
  • 151. Thread communication (Channels) Unless two goroutines can communicate, they can't coordinate. Go has a type called a channel that provides communication and synchronization capabilities. It also has special control structures that build on channels to make concurrent programming easy. 151
  • 152. Channel type In its simplest form the type looks like this: With a value of this type, you can send and receive items of elementType. Channels are a reference type, which means if you assign one chan variable to another, both variables access the same channel. It also means you use make to allocate one: 152
  • 153. The communication operator: <- The arrow points in the direction of data flow. As a binary operator, <- sends the value on the right to the channel on the left: As a prefix unary operator, <- receives from a channel: 153
  • 154. Semantics By default, communication is synchronous. (We'll talk about asynchronous communication later.) This means: 1) A send operation on a channel blocks until a receiver is available for the same channel. 2) A receive operation for a channel blocks until a sender is available for the same channel. Communication is therefore a form of synchronization: two goroutines exchanging data through a channel synchronized at the moment of communication. 154
  • 155. Let’s pump some data Now we start a looping receiver. You can still sneak in and grab a value: 155
  • 156. Functions returning channels In the previous example, pump was like a generator spewing out values. But there was a lot of fuss allocating channels etc. Let's package it up into a function returning the channel of values. 156
  • 157. Range & Channels The range clause on for loops accepts a channel as an operand, in which case the for loops over the values received from the channel. We rewrote pump; here's the rewrite for suck, making it launch the goroutine as well: 157
  • 158. Closing channel How does range know when the channel is done delivering data? The sender calls the built-in function close: close(ch) Receiver tests if the sender has closed the channel using "comma ok": val, ok := <-ch 
 Result is (value, true) while values are available; once channel is closed and drained, result is (zero, false). 158
  • 159. Range on a channel, by hand A for range on a channel such as: is equivalent to: 159
  • 160. Close Only the sender should call close.
 Only the receiver can ask if channel has been closed. Can only ask while getting a value (avoids races). Call close only when it's necessary to signal to the receiver that no more values will arrive. Most of the time, close isn't needed; it's not analogous to closing a file. Channels are garbage-collected regardless. 160
  • 161. Channel directionality 1/2 In its simplest form a channel variable is an unbuffered (synchronous) value that can be used to send and receive. A channel type may be annotated to specify that it may only send or only receive: 161
  • 162. Channel directionality 2/2 All channels are created bidirectional, but we can assign them to directional channel variables. Useful for instance in functions, for (type) safety: 162
  • 163. Synchronous channel Output: sending 10 (happens immediately) sent 10 (60s later, these 2 lines appear) received 10 163
  • 164. Asynchronous channels A buffered, asynchronous channel is created by telling make the number of elements in the buffer. Output: sending 10 (happens immediately) sent 10 (now) received 10 (60s later) 164
  • 165. Buffer is not part of the type Note that the buffer's size, or even its existence, is not part of the channel's type, only of the value. This code is therefore legal, although dangerous: Buffering is a property of the value, not of the type. 165
  • 168. Select Select is a control structure in Go analogous to a communications switch statement. Each case must be a communication, either send or receive. Select executes one runnable case at random. If no case is runnable, it blocks until one is. A default clause is always runnable. 168
  • 169. Random bit generator Prints 0 1 1 0 0 1 1 1 0 1 ... 169
  • 170. Testing for communicability Can a communication proceed without blocking? Select with a default clause can tell us: The default clause executes if no other case can proceed, so this is the idiom for non-blocking receive; non-blocking send is the obvious variant. 170
  • 171. Timeout Can a communication succeed in a given interval? Package time contains the After function: It delivers a value (the current time) on the returned channel after the specified interval. Use it in select to implement timeout: 171
  • 172. Multiplexing Channels are first-class values, which means they can be sent over channels. This property makes it easy to write a service multiplexer since the client can supply, along with its request, the channel on which to reply, Or more typically 172
  • 174. Starting the server Use the "function returning channel" idiom to create a channel to a new server: 174
  • 175. The client A similar example is worked in more detail in the tutorial, but here's a variant: Requests are ready; send them: Can retrieve results in any order; r.replyc demuxes: 175
  • 176. Teardown In the multiplex example, the server runs forever. To tear it down cleanly, signal with a channel. This server has the same functionality but with a quit channel: 176
  • 177. Starting the server The rest of the code is mostly the same, with an extra channel: 177
  • 178. Teardown: the client The client is unaffected until it's ready to shut down the server: All done, signal server to exit: 178
  • 179. Concurrency issues Many issues, of course, but Go tries to take care of them. Channel send and receive are atomic. The select statement is very carefully defined and implemented, etc. But goroutines run in shared memory, communication networks can deadlock, multithreaded debuggers suck, and so on. What to do? 179
  • 180. Go primitives Don't program the way you would in C or C++ or even Java. Channels give you synchronization and communication both, and that makes them powerful but also easy to reason about if you use them well. The rule is: Do not communicate by sharing memory. Instead, share memory by communicating. The very act of communication guarantees synchronization! 180
  • 181. Agenda 3° Day Agenda • Concurrent programming • File Handling • Linking C shared libs • Exercises 181
  • 182. Go: I/O • The two main interfaces are Reader and Writer. • Many functions in Go take Readers or Writers as arguments. • For example the io package has a Copy function which copies data from a Reader to a Writer To read or write to a []byte or a string you can use the Buffer struct found in the bytes package: 182
  • 183. Files: basic operations: read 1/2 Open & read file 183
  • 184. Files: basic operations: read 2/2 There's a shorter way to read a file 184
  • 185. Files: basic operations: create Create a file “test.txt” and write test in content 185
  • 186. Files: basic operations: read a directory 1/2 Read directory “.” and get file infos 186
  • 188. Agenda 3° Day Agenda • Concurrent programming • File Handling • Linking C shared libs • Exercises 188
  • 189. cgo 1/2 • Cgo enables the creation of Go packages that call C code. • To use cgo write normal Go code that imports a pseudo-package "C". 189
  • 190. cgo 1/2 package main /* #cgo CFLAGS: -I./ #cgo LDFLAGS: -L. -lkeyboard #include <keyboard.h> */ import "C" import ( "fmt" ) func main() { C.InitKeyboard() fmt.Printf("nEnter: ") for { r := C.GetCharacter() fmt.Printf("%c", r) if r == 'q' { break } } C.CloseKeyboard() } 1. CFLAGS:parameters to the compiler. 2. ./ folder: compilercan find our header files. 3. LDFLAGS: parameters to the linker. 4. -L: (minus capital L) which tells the linker where it can find our dynamic library 5. -l: (minus lowercase L) which tells the linker the name of our library. 190
  • 191. Agenda 3° Day Agenda • Concurrent programming • File Handling • Linking C shared libs • Exercises 191
  • 192. Exercises • Read dir • Analize file extension • apply regular expression file content • multithread mode 192
  • 193. Agenda 4° Day Agenda • Gorilla web toolkit (Go Web Application Toolkit) • Gorm (Go ORM) • Exercises 193
  • 194. Overview Web Toolkit build with go • gorilla/context: stores global request variables. • gorilla/mux: is a powerful URL router and dispatcher. • gorilla/reverse: produces reversible regular expressions for regexp-based muxes. • gorilla/rpc: implements RPC over HTTP with codec for JSON-RPC. • gorilla/schema: converts form values to a struct. • gorilla/securecookie encodes and decodes authenticated and optionally encrypted cookie values. • gorilla/sessions: saves cookie and filesystem sessions and allows custom session backends. • gorilla/websocket: implements the WebSocket protocol defined in RFC 6455. 194
  • 197. Agenda 4° Day Agenda • Gorilla web toolkit (Go Web Application Toolkit) • Gorm (Go ORM) • Exercises 197
  • 198. Overview Gorm is ORM (Object Relational Mapper) library for Golang • Full-Featured ORM (almost) • Chainable API • Auto Migrations • Relations (Has One, Has Many, Belongs To, Many To Many, Polymorphism) • Callbacks (Before/After Create/Save/Update/Delete/Find) • Preloading (eager loading) • Transactions • Embed Anonymous Struct • Soft Deletes • Customizable Logger • Iteration Support via Rows • Every feature comes with tests • Developer Friendly 198
  • 199. Installation Gorm toolkit: go get -u github.com/jinzhu/gorm Postgresql driver: go get github.com/lib/pq Gorilla web toolkit: go get github.com/gorilla/mux 199