Introduction to the Go Programming Language

Similar documents
Go Tutorial. Ian Lance Taylor. Introduction. Why? Language. Go Tutorial. Ian Lance Taylor. GCC Summit, October 27, 2010

ITI Introduction to Computing II

ITI Introduction to Computing II

Google Go illustrated on the basis of Fibonacci numbers

#29: Logarithm review May 16, 2009

Computer Science Introductory Course MSc - Introduction to Java

Python. chrysn

Clojure Concurrency Constructs, Part Two. CSCI 5828: Foundations of Software Engineering Lecture 13 10/07/2014

Lab 2: Static Response, Cantilevered Beam

Python & Numpy A tutorial

Lecture 8 HASHING!!!!!

INTRODUCTION. This is not a full c-programming course. It is not even a full 'Java to c' programming course.

1 Trees. Listing 1: Node with two child reference. public class ptwochildnode { protected Object data ; protected ptwochildnode l e f t, r i g h t ;

Lecture 4: Constructing the Integers, Rationals and Reals

INF 4140: Models of Concurrency Series 3

Introduction to Python

Proof Techniques (Review of Math 271)

4.4 The Calendar program

( )( b + c) = ab + ac, but it can also be ( )( a) = ba + ca. Let s use the distributive property on a couple of

Notater: INF3331. Veronika Heimsbakk December 4, Introduction 3

Octave. Tutorial. Daniel Lamprecht. March 26, Graz University of Technology. Slides based on previous work by Ingo Holzmann

Designing Information Devices and Systems I Fall 2018 Lecture Notes Note Introduction to Linear Algebra the EECS Way

import java. u t i l. ;... Scanner sc = new Scanner ( System. in ) ;

Tutorial Three: Loops and Conditionals

Predictive parsing as a specific subclass of recursive descent parsing complexity comparisons with general parsing

5 + 9(10) + 3(100) + 0(1000) + 2(10000) =

CSCI3390-Assignment 2 Solutions

Math 31 Lesson Plan. Day 2: Sets; Binary Operations. Elizabeth Gillaspy. September 23, 2011

COMS 6100 Class Notes

Reading and Writing. Mathematical Proofs. Slides by Arthur van Goetham

CISC 4090: Theory of Computation Chapter 1 Regular Languages. Section 1.1: Finite Automata. What is a computer? Finite automata

Moving into the information age: From records to Google Earth

1 Closest Pair of Points on the Plane

Announcements. Problem Set 6 due next Monday, February 25, at 12:50PM. Midterm graded, will be returned at end of lecture.

Designing Information Devices and Systems I Spring 2018 Lecture Notes Note Introduction to Linear Algebra the EECS Way

MiniMat: Matrix Language in OCaml LLVM

Math 31 Lesson Plan. Day 5: Intro to Groups. Elizabeth Gillaspy. September 28, 2011

Introduction to Python

ECEN 651: Microprogrammed Control of Digital Systems Department of Electrical and Computer Engineering Texas A&M University

Lecture 3. Big-O notation, more recurrences!!

Math 3361-Modern Algebra Lecture 08 9/26/ Cardinality

Turing Machines Part Three

1 ListElement l e = f i r s t ; / / s t a r t i n g p o i n t 2 while ( l e. next!= n u l l ) 3 { l e = l e. next ; / / next step 4 } Removal

Lectures about Python, useful both for beginners and experts, can be found at (

Chapter 2. Mathematical Reasoning. 2.1 Mathematical Models

Week 2: Defining Computation

Computer Science 324 Computer Architecture Mount Holyoke College Fall Topic Notes: Digital Logic

Lisp Introduction. Dr. Neil T. Dantam. Spring CSCI-498/598 RPM, Colorado School of Mines. Dantam (Mines CSCI, RPM) Lisp Spring / 88

Hypothesis testing I. - In particular, we are talking about statistical hypotheses. [get everyone s finger length!] n =

Comp 11 Lectures. Mike Shah. July 12, Tufts University. Mike Shah (Tufts University) Comp 11 Lectures July 12, / 33

CSE 331 Winter 2018 Homework 1

(a) Definition of TMs. First Problem of URMs

CS 124 Math Review Section January 29, 2018

MITOCW ocw-18_02-f07-lec02_220k

Please bring the task to your first physics lesson and hand it to the teacher.

What Every Programmer Should Know About Floating-Point Arithmetic DRAFT. Last updated: November 3, Abstract

Getting Started with Communications Engineering

One-to-one functions and onto functions

Algebra Exam. Solutions and Grading Guide

Example: 2x y + 3z = 1 5y 6z = 0 x + 4z = 7. Definition: Elementary Row Operations. Example: Type I swap rows 1 and 3

Cosets and Lagrange s theorem

An analogy from Calculus: limits

Binary addition example worked out

Chapter 1. Foundations of GMAT Math. Arithmetic

CE 365K Exercise 1: GIS Basemap for Design Project Spring 2014 Hydraulic Engineering Design

: Intro Programming for Scientists and Engineers Assignment 4: Learning from Echocardiograms

2 Systems of Linear Equations

Error Correcting Codes Prof. Dr. P. Vijay Kumar Department of Electrical Communication Engineering Indian Institute of Science, Bangalore

Hoare Logic: Reasoning About Imperative Programs

CSE 331 Winter 2018 Reasoning About Code I

Unit 8: Sequ. ential Circuits

Ratios, Proportions, Unit Conversions, and the Factor-Label Method

C if U can. Algebra. Name

Using Microsoft Excel

Anatomy of SINGULAR talk at p. 1

Turing Machines Part II

1 Maintaining a Dictionary

R: A Quick Reference

And, even if it is square, we may not be able to use EROs to get to the identity matrix. Consider

CS173 Lecture B, November 3, 2015

One sided tests. An example of a two sided alternative is what we ve been using for our two sample tests:

Math101, Sections 2 and 3, Spring 2008 Review Sheet for Exam #2:

Satellite project, AST 1100

Lecture 27: Theory of Computation. Marvin Zhang 08/08/2016

Experiment 1: The Same or Not The Same?

Turing Machine Recap

CS1800: Mathematical Induction. Professor Kevin Gold

Ch. 3 Equations and Inequalities

CHAPTER 7: TECHNIQUES OF INTEGRATION

Course Announcements. John Jannotti (cs32) Scope, Collections & Generics Feb 8, / 1

Confidence intervals

Blocking Synchronization: Streams Vijay Saraswat (Dec 10, 2012)

Scripting Languages Fast development, extensible programs

Math 308 Midterm Answers and Comments July 18, Part A. Short answer questions

MA554 Assessment 1 Cosets and Lagrange s theorem

Final Review Sheet. B = (1, 1 + 3x, 1 + x 2 ) then 2 + 3x + 6x 2

An Introduction to Z3

1 Definition of a Turing machine

SUPPLEMENTARY INFORMATION

CMSC 451: Lecture 7 Greedy Algorithms for Scheduling Tuesday, Sep 19, 2017

Transcription:

Introduction to the Go Programming Language Fabian Wenzelmann August 1, 2017 F. Wenzelmann Introduction to Go August 1, 2017 1 / 126

Why Go? What is Go? Go is a programming language developed at Google It is free and open source, available for Linux, Windows and Apple OS X Some buzzwords Compiled Statically typed Provides garbage collection Features concurrent programming F. Wenzelmann Introduction to Go August 1, 2017 2 / 126

Hello World package main import ( fmt ) f u n c main ( ) { fmt. P r i n t l n ( H e l l o World! ) Try on Go Playground: https://play.golang.org/p/f13xofyiv- F. Wenzelmann Introduction to Go August 1, 2017 3 / 126

Installing Go I We will do some small exercises togehter, to follow this you need to install Go I recommend using Go 1.7 Follow instructions here: https://golang.org/doc/install, install from.tar Don t forget to set $GOPATH git clone https://git.fabianwen.de/fabian/golangsrc in your src directory... or clone it somewhere and use docker: 1 docker-compose up 2 docker-compose exec golang /bin/bash F. Wenzelmann Introduction to Go August 1, 2017 4 / 126

Installing Go II Test your installation: go install golangsrc/examples/helloworld Execute /go/bin/helloworld (or whatever your gopath is) Most of the examples from the slides can be found in golangsrc/examples Exercise templates (most of them can t be compiled until you do the exercise) in golangsrc/exercises F. Wenzelmann Introduction to Go August 1, 2017 5 / 126

Toward Go 2 On July 13, 2017 Go version 2 was announced: https://blog.golang.org/toward-go2 There is a plan on how the developers will proceed Go 2 will be compatible with Go 1 code No fixed schedule yet F. Wenzelmann Introduction to Go August 1, 2017 6 / 126

Defining Functions Function definition with the func keyword The type of a variable / function comes after the variable name / function name You don t use a semicolon to end a statement f u n c IntMax ( a i n t, b i n t ) i n t { i f a > b { r e t u r n a e l s e { r e t u r n b Playground: https://play.golang.org/p/oeqntd5uzv F. Wenzelmann Introduction to Go August 1, 2017 7 / 126

Variables and Types Builtin Types Many types for ints and floats (numeric types) int8, int16, int32, int64: architecture-independent for n-bit integers There are also unsigned n-bit integers like uint8, uint16,... float32, float64 complex64, complex128 byte is an alias of uint8 bool predeclared constants true and false string is a sequence of bytes. We ll come to that later. Numeric Types When working with ints you usually work with the implementation-specific types int and uint which is either a 32 or 64 bit integer. F. Wenzelmann Introduction to Go August 1, 2017 8 / 126

Variables and Types Defining a Variable There are different ways of defining a variable: f u n c main ( ) { v a r i i n t = 21 v a r j i n t j = 42 k := 84 // s h o r t a s s i g n m e n t s t a t e m e n t fmt. P r i n t l n ( i, j, k ) Playground: https://play.golang.org/p/q8rmxk8hzy Short assignment statements can be used inside function definitions, the type in this example is int. F. Wenzelmann Introduction to Go August 1, 2017 9 / 126

Variables and Types About Types and Conversions Go doesn t do automatic type conversions, you have to do it explictly int is a new type that is either int32 or int64, but it is not an alias for it! v a r i i n t 6 4 = 42 v a r j i n t = i cannot use i (type int64) as type int in assignment v a r j i n t = i n t ( i ) An exception is byte which is really an alias for uint8 F. Wenzelmann Introduction to Go August 1, 2017 10 / 126

Case Distinction If-Else and Switches I If-Else statements don t require parentheses, but braces are required You can only use type bool in if statements There is no thing like pythons elif, a switch statement is heavily used in Go f u n c RateNumber (num i n t ) { i f num == 42 { fmt. P r i n t l n ( The answer to e v e r y t h i n g ) e l s e i f num == 21 { fmt. P r i n t l n ( Only h a l f the t r u t h ) e l s e { fmt. P r i n t l n ( What a lame number ) F. Wenzelmann Introduction to Go August 1, 2017 11 / 126

Case Distinction If-Else and Switches II f u n c RateNumber (num i n t ) { s w i t c h num { c a s e 4 2 : fmt. P r i n t l n ( The answer to e v e r y t h i n g ) c a s e 2 1 : fmt. P r i n t l n ( Only h a l f the t r u t h ) d e f a u l t : fmt. P r i n t l n ( What a lame number ) Playground: https://play.golang.org/p/nn2n5ryl0e F. Wenzelmann Introduction to Go August 1, 2017 12 / 126

Case Distinction About the Switch Statement I Switches work with many types, for example strings Cases are evaluated from top to bottom and the switch stops when a case succeeds If you want a fallthrough behaviour like in C++ use the fallthrough keyword at the end of the case If no variable is specified, a switch on the first case that evaluates to true is performed You can specifiy multiple values in one case, separated by comma F. Wenzelmann Introduction to Go August 1, 2017 13 / 126

Case Distinction About the Switch Statement II f u n c WakeUp( h i n t ) { s w i t c h { c a s e h < 1 1 : fmt. P r i n t l n ( Eeeew, t h a t e a r l y? ) c a s e h > 1 5 : fmt. P r i n t l n ( Had some fun l a s t n i g h t? ) d e f a u l t : fmt. P r i n t l n ( Seems p r e t t y normal to me. ) Playground: https://play.golang.org/p/qbwqu0o1xp F. Wenzelmann Introduction to Go August 1, 2017 14 / 126

Loops The For Loop I There is only one statement in Go for a loop, for There are different variations of this statement: f u n c PrintNumbers ( s t a r t, end i n t ) { f o r i := s t a r t ; i < end ; i++ { fmt. P r i n t l n ( i ) Playground: https://play.golang.org/p/wv6jk69ioz F. Wenzelmann Introduction to Go August 1, 2017 15 / 126

Loops The For Loop II The init and post statements are optional Just put the ; there and leave the commands blank continue and break are supported f u n c F a c t o r i a l ( n u i n t ) u i n t { v a r r e s u i n t = 1 v a r i u i n t = 1 f o r ; i <= n ; i++ { r e s = i r e t u r n r e s Playground: https://play.golang.org/p/vtez5fuult F. Wenzelmann Introduction to Go August 1, 2017 16 / 126

Loops The For Loop III If you want something like a while loop use for with just a condition: f o r i < n { // your code h e r e For an infinite loop skip even that: f o r { // your code h e r e F. Wenzelmann Introduction to Go August 1, 2017 17 / 126

Loops Switches in a for-loop I Caution Be careful that the break statement breaks a switch statement as well as a for loop! So using break in a switch statement inside a for loop breaks the switch, not the for! F. Wenzelmann Introduction to Go August 1, 2017 18 / 126

Loops Switches in a for-loop II We want define a function that prints the first number i between start and end that is divisible by num The following code is wrong f u n c P r i n t D i v i s i b l e ( s t a r t, end, num i n t ) { f o r i := s t a r t ; i <= end ; i++ { s w i t c h { c a s e i%num == 0 : fmt. P r i n t f ( F i r s t number d i v i s i b l e by %d i s %d\n, num, i ) b reak Playground: https://play.golang.org/p/ccvbyjbgde F. Wenzelmann Introduction to Go August 1, 2017 19 / 126

Loops Switches in a for-loop III You have to create a label for breaking the loop in this case: f u n c P r i n t D i v i s i b l e ( s t a r t, end, num i n t ) { Loop : f o r i := s t a r t ; i <= end ; i++ { s w i t c h { c a s e i%num == 0 : fmt. P r i n t f ( F i r s t number d i v i s i b l e by %d i s %d\n, num, i ) b reak Loop Playground: https://play.golang.org/p/w2k4uu0_oj F. Wenzelmann Introduction to Go August 1, 2017 20 / 126

Loops Switches in a for-loop IV The same problem with break occurs when using a select statement (later) When working with switches in loops it s usually a good idea to use a label and use break / continue with the label F. Wenzelmann Introduction to Go August 1, 2017 21 / 126

Loops Exercise Session 1 I Before we start the exercises: You should either copy the template from the exercises directory into mysolutions... or edit the template files directly, make sure to keep the directory structure Sample solutions are in solutions, but this spoils the fun The exercises are not very challenging, you should just get familiar with Go cd into the directory containing the.go file and compile with go build FILENAME.go This creates an executable called FILENAME F. Wenzelmann Introduction to Go August 1, 2017 22 / 126

Loops Exercise Session 1 II Exercise Template: exercises/prime (a) Implement a function I s P r i m e ( n u i n t ) b o o l that tests if n is prime number (b) In the main() function print the first 100 prime numbers F. Wenzelmann Introduction to Go August 1, 2017 23 / 126

Loops Exercise Session 1 III Exercise Template: exercises/exp Implement a method Exp ( x, e p s i l o n f l o a t 6 4 ) f l o a t 6 4 That computes e x with the following sum: e x = Stop when two consecutive sums differ by a value < ε where ε > 0. n=0 x n n! F. Wenzelmann Introduction to Go August 1, 2017 24 / 126

Strings, Arrays and Slices Arrays Arrays are very important, but you don t use them very often directly - instead you use slices An array of type T of size n is declared as var array [n]t Note that var array [n]t and var array [m]t are different types for n m The elements are initialized with a default value (0 for numbers) Access as in other languages: array[i] Example: https://play.golang.org/p/xzpd-j2cet F. Wenzelmann Introduction to Go August 1, 2017 25 / 126

Strings, Arrays and Slices Working With Arrays Arrays are not passed by reference, you ll always get a copy when passing it to a function / assigning an existing array to a variable Example: https://play.golang.org/p/lkyq1wdob8 Instead of arrays you usually use a slice F. Wenzelmann Introduction to Go August 1, 2017 26 / 126

Strings, Arrays and Slices Slices I A slice describes a part of an array A slice of type T has the signature []T and it can be created from an array given the start and end position Don t pass a pointer to a slice, pass the array directly (this does not copy the content of the underlying array) Create a slice from an array with a[start:end] Chaning the value s[i] = something changes the value in the underlying array Example: https://play.golang.org/p/hl81cgmarh F. Wenzelmann Introduction to Go August 1, 2017 27 / 126

Strings, Arrays and Slices Slices II You can also create a slice from an existing one and get / set an element out of a slice using the same notation as with arrays: v a r a r r a y [ 4 ] i n t a r r a y [ 0 ] = 1 a r r a y [ 1 ] = 2 a r r a y [ 2 ] = 3 a r r a y [ 3 ] = 4 s1 := a r r a y [ 1 : 4 ] s2 := s1 [ 1 : 2 ] fmt. P r i n t l n ( s2 ) fmt. P r i n t l n ( s1 [ 0 ] ) fmt. P r i n t l n ( s2 [ 0 ] ) Playground: https://play.golang.org/p/23-hdnqwqc F. Wenzelmann Introduction to Go August 1, 2017 28 / 126

Strings, Arrays and Slices Slices in Action A slice can be used as you use a vector in other programming languages You can append elements to a slice, if the underlying array is not big enough a new one will be allocated This especially means that if a slice grows bigger than its capacity you don t reference the same array as before! You can determine the size of a slice with len(s) A slice also has a capacity, which stores how much space the underlying array has: cap(s) Further reading: https://blog.golang.org/slices F. Wenzelmann Introduction to Go August 1, 2017 29 / 126

Strings, Arrays and Slices Slice Examples I To create an empty slice of type T you can use the make method: s := make ( [ ] i n t, 5) This will create a slice containing five elements (all 0) You can also specify the a capacity (the size of the underlying array): s := make ( [ ] i n t, 5, 10) The length of this slice is 5, but if you append another element there is no need to create a new array Example on Playground: https://play.golang.org/p/znhup7u18g F. Wenzelmann Introduction to Go August 1, 2017 30 / 126

Strings, Arrays and Slices Slice Examples II The append function appends an element to a slice and returns a new slice (remember that the array underneath can change) You can also pass more than one element to append s := make ( [ ] i n t, 1, 1) s = append ( s, 1) fmt. P r i n t l n ( s :, s ) s2 := s [ : ] s [ 0 ] = 21 s2 = append ( s2, 2, 3) fmt. P r i n t l n ( s2 :, s2 ) s [ 1 ] = 42 fmt. P r i n t l n ( s a f t e r m o d i f i c a t i o n o f s :, s ) fmt. P r i n t l n ( s2 a f t e r m o d i f i c a t i o n o f s :, s2 ) Try on the Playground: https://play.golang.org/p/01lvaqsbcv F. Wenzelmann Introduction to Go August 1, 2017 31 / 126

Strings, Arrays and Slices Iterating Over Slices You can iterate over a slice with for i := 0; i < len(s); i++ Or you can use the function range (more common): f o r i, v := range s { fmt. P r i n t f ( Element on p o s i t i o n %d i s %v\n, i, v ) An example on the Playground: https://play.golang.org/p/9uehcrxrek If you re not interested in the position of an element name the variable There is an alternative method for creating a slice given an enumeration of its values: s := [ ] f l o a t 6 4 { 0. 5, 1 0. 2 5, 2 1. 7 5, 42.5 F. Wenzelmann Introduction to Go August 1, 2017 32 / 126

Strings, Arrays and Slices Strings The builtin type string is often used in the wrong way... For Go a string is just a (read-only) slice of bytes Go doesn t care if it is encoded in ASCII, UTF-8 or something else The notation str[k] returns the k-th byte in the string: v a r s t r s t r i n g = f o o bar fmt. P r i n t l n ( s t r ) fmt. P r i n t l n ( s t r [ 4 : ] ) fmt. P r i n t l n ( l e n ( s t r ) ) fmt. P r i n t l n ( s t r [ 1 ] ) Playground: https://play.golang.org/p/2st1wevt1_ F. Wenzelmann Introduction to Go August 1, 2017 33 / 126

Strings, Arrays and Slices Strings and UTF-8 strings are encoded in UTF-8: s t r := e fmt. P r i n t l n ( s t r ) fmt. P r i n t l n ( l e n ( s t r ) ) Playground: https://play.golang.org/p/arxie6tgnz UTF-8 uses a different number of bytes, depending on the encoded char (e for example requires three bytes) So a for loop f o r i := 0 ; i < l e n ( s t r ) ; i++ {... should not be used to iterate over each character! F. Wenzelmann Introduction to Go August 1, 2017 34 / 126

Strings, Arrays and Slices rune Go uses a special type rune, which is an int32. This is a unicode codepoint The words character, codepoint etc. are used in an ambiguous way... What you know as a character in other languages can be thought of as a Go rune Rune constants are enclosed in single quotes in Go. For example 本 is mapped to the integer value 26412 (requires three bytes) Further reading: https://blog.golang.org/strings F. Wenzelmann Introduction to Go August 1, 2017 35 / 126

Strings, Arrays and Slices Using Strings You can concatenate strings with +: H e l l o + World We can also use the range function, this however treats strings in a special way! Instead of iterating over the bytes the function decodes one UTF-8 encoded rune in each iteration, the index of the loop is the starting position of the current rune. Note that some byte sequences are not valid UTF-8 points The package unicode/utf8 has some useful functions for working with strings and runes Other useful packages: 1 strings: Manipulate UTF-8 encoded strings 2 strconv: Conversion from and to basic types 3 regexp: Regular expressions F. Wenzelmann Introduction to Go August 1, 2017 36 / 126

Strings, Arrays and Slices Strings and Memory It s important to note that strings are just slices Therefor they refer to an array somewhere in the memory This can lead to memory problems: For example you load a big file in memory but you re only interested in some part of it If you get the part you re interested in by creating a slice or using some method from strings that only returns a slice of the existing string... the big array referenced by that slice will never be deleted by the garbage collection In such cases you should make a copy, use the copy function F. Wenzelmann Introduction to Go August 1, 2017 37 / 126

Other Basic Stuff Advanced Function Definitions I A function can have multiple return values (like tuples in python) and you can define multiple variables at once However there is no tuple type which you can use outside a function definition / variable initialization (kind of sad) A function can take an arbitrary number of arguments (of a certain type) Those elements are passed to the function as a slice F. Wenzelmann Introduction to Go August 1, 2017 38 / 126

Other Basic Stuff Advanced Function Definitions II f u n c MinMax ( a i n t, e l e m e n t s... i n t ) ( i n t, i n t ) { min, max := a, a f o r, v a l := range e l e m e n t s { s w i t c h { c a s e v a l < min : min = v a l c a s e v a l > max : max = v a l r e t u r n min, max Playground: https://play.golang.org/p/3yzwuoydky F. Wenzelmann Introduction to Go August 1, 2017 39 / 126

Other Basic Stuff Advanced Function Definitions III A function that accepts multiple values like elements...int can also be called with a slice of that type: s := [ ] i n t {3, 2, 5, 1, 1 MinMax ( 1, s... ) Functions can be passed as arguments to functions and functions can return functions. Go also supports anonymous functions and closures F. Wenzelmann Introduction to Go August 1, 2017 40 / 126

Other Basic Stuff Advanced Function Definitions IV f u n c Chain ( f, g f u n c ( i n t ) i n t ) f u n c ( i n t ) i n t { r e t u r n f u n c ( n i n t ) i n t { r e t u r n f ( g ( n ) ) f u n c main ( ) { d o u b l e := f u n c ( n i n t ) i n t { r e t u r n 2 n addone := f u n c ( n i n t ) i n t { r e t u r n n + 1 fmt. P r i n t l n ( Chain ( double, addone ) ( 5 ) ) Playground: https://play.golang.org/p/6bu2tv47la F. Wenzelmann Introduction to Go August 1, 2017 41 / 126

Other Basic Stuff Advanced Function Definitions V f u n c F i b o n a c c i ( ) f u n c ( ) u i n t { v a r a, b u i n t = 0, 1 r e t u r n f u n c ( ) u i n t { r e s := a a, b = b, a+b r e t u r n r e s f u n c main ( ) { f i b := F i b o n a c c i ( ) f o r i := 0 ; i < 1 5 ; i++ { fmt. P r i n t l n ( f i b ( ) ) Playground: https://play.golang.org/p/_vapwqehsv F. Wenzelmann Introduction to Go August 1, 2017 42 / 126

Other Basic Stuff Exercise Session 2 I Exercise Template: exercises/mutliplyslice Implement a function M u l t i p l y S l i c e ( s [ ] i n t, num i n t ) [ ] i n t that repeats the slice s num times and returns the new slice. s := [ ] i n t {1, 2, 3 fmt. P r i n t l n ( M u l t i p l y S l i c e ( s, 3 ) ) [ 1 2 3 1 2 3 1 2 3 ] F. Wenzelmann Introduction to Go August 1, 2017 43 / 126

Other Basic Stuff Exercise Session 2 II Exercise Template: exercises/palindrome Implement a function I s P a l i n d r o m e ( s s t r i n g ) b o o l that checks if s is a palindrome (ignoring cases). A palindrome is a string that reads the same backwards and forwards. Hint: Use []rune(s) to convert a string to a slice of runes. F. Wenzelmann Introduction to Go August 1, 2017 44 / 126

Other Basic Stuff Exercise Session 2 III Exercise Template: exercises/curry Implement a function Curry ( f f u n c ( x, y i n t ) i n t, x i n t ) f u n c ( y i n t ) i n t s.t. Curry(f, x)(y) evaluates to f(x, y). F. Wenzelmann Introduction to Go August 1, 2017 45 / 126

Other Basic Stuff Maps I The type map[keytype]valuetype implements dictionaries The KeyType is rather restricted, more information may be found here: https://blog.golang.org/go-maps-in-action However we can use int, string,... Short example: age := map [ s t r i n g ] i n t { Bob : 42, Susan : 21 age [ John ] = 84 fmt. P r i n t l n ( age [ Bob ] ) Playground: https://play.golang.org/p/_eimqb_tg4 F. Wenzelmann Introduction to Go August 1, 2017 46 / 126

Other Basic Stuff Maps II Remove an entry for key (if this is not a valid key nothing will happen): d e l e t e ( age, Bob ) d e l e t e ( age, George ) F. Wenzelmann Introduction to Go August 1, 2017 47 / 126

Other Basic Stuff Maps III To check if a value exists you can use a two-value assignment Otherwise you get the default value of the value type agesusan, hassusan := age [ Susan ] agebob, hasbob := age [ Bob ] i f hassusan { fmt. P r i n t l n ( Age o f Susan i s, agesusan ) e l s e { fmt. P r i n t l n ( No e n t r y f o r Susan ) i f hasbob { fmt. P r i n t l n ( Age o f Bob i s, agebob ) e l s e { fmt. P r i n t l n ( No e n t r y f o r Bob ) Playground: https://play.golang.org/p/lbpl7z1oqy F. Wenzelmann Introduction to Go August 1, 2017 48 / 126

Other Basic Stuff Maps IV Iterate over a map with range: f o r key, v a l u e := range age { fmt. P r i n t l n ( Age o f, key, i s, v a l u e ) Playground: https://play.golang.org/p/mjuzwtftyd It is safe to delete keys from a map while iterating over it with range Maps and slices are not safe to read / write concurrently from different goroutines, protect for example with a RWMutex F. Wenzelmann Introduction to Go August 1, 2017 49 / 126

Other Basic Stuff Pointers A pointer holds the memory address of a variable For a type T there is also a type *T The operator & generates a pointer from a variable, the operator * denotes the underlying value f u n c Swap ( a, b i n t ) { a, b = b, a f u n c main ( ) { a := 21 b := 42 Swap(&a, &b ) fmt. P r i n t l n ( a =, a, b =, b ) Playground: https://play.golang.org/p/076wjmx9nc F. Wenzelmann Introduction to Go August 1, 2017 50 / 126

Other Basic Stuff nil The special type nil is what you know as null pointer from other languages Technically nil is not a type, nil can be used for different types such as pointers, slices, maps A slice can be nil and the slice functions will treat it as an empty slice So an empty slice can be defined like: v a r s [ ] i n t = n i l Or even just v a r s [ ] i n t F. Wenzelmann Introduction to Go August 1, 2017 51 / 126

Structs and Interfaces Structs Structs are used to group fields They don t work as classes as you know them from Java or other languages! You can define functions for your structs and they can be called with the dot notation F. Wenzelmann Introduction to Go August 1, 2017 52 / 126

Structs and Interfaces Defining Structs t y p e R e c t a n g l e s t r u c t { Width, Height f l o a t 6 4 f u n c ( r R e c t a n g l e ) Area ( ) f l o a t 6 4 { r e t u r n r. Width r. Height f u n c main ( ) { r1 := R e c t a n g l e {5, 10 r2 := R e c t a n g l e {Width : 10, Height : 20 fmt. P r i n t l n ( r1. Area ( ), r2. Area ( ) ) Playground: https://play.golang.org/p/4rgxqs4utw F. Wenzelmann Introduction to Go August 1, 2017 53 / 126

Structs and Interfaces Receivers Area is a so called pointer receiver, because the Rectangle object is passed by pointer In contrast a value receiver does not receive a pointer but an actual struct value However in this case a copy of the struct is created and passed to the function, thus changes made to the struct are not present in the object you called the method on In most cases pointer receivers are the best option Slices and Maps Note that slices, strings and maps must not be passed as pointers. They re lightweight structs. F. Wenzelmann Introduction to Go August 1, 2017 54 / 126

Structs and Interfaces Constructors I There is no such thing as a constructor in Go Instead for a struct T you usually define a method NewT(args) that returns a pointer to a new object: f u n c NewRectangle ( width, h e i g h t f l o a t 6 4 ) R e c t a n g l e { r e t u r n &R e c t a n g l e {Width : width, Height : h e i g h t F. Wenzelmann Introduction to Go August 1, 2017 55 / 126

Structs and Interfaces Constructors II You may have noticed the two different ways to create a new object: r1 := R e c t a n g l e {5, 10 r2 := R e c t a n g l e {Width : 10, Height : 20 The first one lists the elements in the order as defined in the struct definition, the second one uses name / value pairs The second one is much cleaner and easier to read! I don t know why this feature is not available for function calls... F. Wenzelmann Introduction to Go August 1, 2017 56 / 126

Structs and Interfaces Interfaces I An interface is a collection of method signatures You don t have to specify that a struct implements an interface, Go determines by itself if this is the case t y p e TwoDObject i n t e r f a c e { Area ( ) f l o a t 6 4 P e r i m e t e r ( ) f l o a t 6 4 Assuming we also defined the Perimeter function, a *Rectangle could be used as a TwoDObject F. Wenzelmann Introduction to Go August 1, 2017 57 / 126

Structs and Interfaces Interfaces II t y p e C i r c l e s t r u c t { Radius f l o a t 6 4 f u n c N e w C i r c l e ( r a d i u s f l o a t 6 4 ) C i r c l e { r e t u r n &C i r c l e { Radius : r a d i u s f u n c ( c C i r c l e ) Area ( ) f l o a t 6 4 { r e t u r n math. Pi c. Radius c. Radius f u n c ( c C i r c l e ) P e r i m e t e r ( ) f l o a t 6 4 { r e t u r n 2. 0 math. Pi c. Radius F. Wenzelmann Introduction to Go August 1, 2017 58 / 126

Structs and Interfaces Interfaces III f u n c P r i n t I n f o ( o b j e c t TwoDObject ) { fmt. P r i n t f ( TwoDObject : Area = %.3 f, P e r i m e t e r = %.3 f \n, o b j e c t. Area ( ), o b j e c t. P e r i m e t e r ( ) ) f u n c main ( ) { r := NewRectangle ( 5, 10) c := N e w C i r c l e ( 5 ) P r i n t I n f o ( r ) P r i n t I n f o ( c ) Complete code on Playground: https://play.golang.org/p/3nc6zfa7rw F. Wenzelmann Introduction to Go August 1, 2017 59 / 126

Structs and Interfaces Interfaces IV Note that if you used a pointer receiver for type T to implement methods for an interface the type *T implements the interface, not T When using interfaces in functions you don t have to pass a pointer to that interface A variable of an interface type can have the value nil F. Wenzelmann Introduction to Go August 1, 2017 60 / 126

Structs and Interfaces Delegators I You can use delegators to delegate methods to another type: t y p e A s t r u c t { f u n c ( a A) Foo ( ) { fmt. P r i n t l n ( Foo on A ) a. Bar ( ) f u n c ( a A) Bar ( ) { fmt. P r i n t l n ( Bar on A ) t y p e B s t r u c t { A // d e l e g a t e methods to A f u n c ( b B) Bar ( ) { fmt. P r i n t l n ( Bar on B ) F. Wenzelmann Introduction to Go August 1, 2017 61 / 126

Structs and Interfaces Delegators II As seen before, all methods not defined in A and don t exist in B are delegated to the A instance Feels like overwriting and inheritance? It isn t! It s the so called composition pattern B is always of type B, and not of type A! Delegators are the same as storing an instance of that type in your struct and defining not implemented function and call the function on that element F. Wenzelmann Introduction to Go August 1, 2017 62 / 126

Structs and Interfaces Defining an Alias for a Type You can define a new type by defining it as something like an alias for that type t y p e I n t S e t map [ i n t ] s t r u c t { But it is a completely new type that only is something like an alias for map[int]interface You can define functions explictly for this type like f u n c ( s e t I n t S e t ) I n s e r t ( v a l i n t ) { s e t [ v a l ] = s t r u c t {{ Playground: https://play.golang.org/p/tbbwzzyopz F. Wenzelmann Introduction to Go August 1, 2017 63 / 126

Structs and Interfaces Consts There are different ways to define const values, see https://blog.golang.org/constants for details Usually you define something like c o n s t GolangHome = h t t p s : / / g o l a n g. org / c o n s t ( Red = r e d Blue = b l u e ) Playground: https://play.golang.org/p/qnzfiqpdqe F. Wenzelmann Introduction to Go August 1, 2017 64 / 126

Structs and Interfaces Enum-like Types I Go doesn t support enum types Instead you usually define an alias of type int Go has an identifier iota that helps you generat sequences Details: https://golang.org/ref/spec#iota We define an enumeration of all days of the week (though this is already done in the time package) F. Wenzelmann Introduction to Go August 1, 2017 65 / 126

Structs and Interfaces Enum-like Types II Define a const block and enumrate the possible values, use iota to enumerate the concrete values: t y p e Weekday i n t c o n s t ( Monday = Weekday ( i o t a ) Tuesday Wednesday Thursday F r i d a y Saturday Sunday ) F. Wenzelmann Introduction to Go August 1, 2017 66 / 126

Structs and Interfaces Enum-like Types III Define some new methods for our new type Hint: It is always useful to define a method String() string, this representation will be used by the print functions: f u n c ( day Weekday ) S t r i n g ( ) s t r i n g { s w i t c h day { c a s e Monday : r e t u r n Monday c a s e Tuesday : r e t u r n Tuesday... d e f a u l t : r e t u r n Unknown day Actually there is a tool for generating code for such types automatically, stringer F. Wenzelmann Introduction to Go August 1, 2017 67 / 126

Structs and Interfaces Enum-like Types IV Why the default case? In Go Weekday is just something like an alias for int You can still pass literals to a function that expects such a type (like an arbitrary integer in this example) This is however not so easy to understand, but is not needed that much You can read more about this here Full code example on the Playground: https://play.golang.org/p/6mtq4yagh3 F. Wenzelmann Introduction to Go August 1, 2017 68 / 126

Structs and Interfaces Some Words About Types Go does not support generics There are some hacks : use interface{ and then cast to the appropriate type This is however not very clean But it can be really annoying to define types like IntSet and StringSet and leads to code duplication No (operator) overloading You can use different types for keys in a dictionary, but the behaviour is rather confusing: See the Comparison Operators in the language spec and the blog post about maps F. Wenzelmann Introduction to Go August 1, 2017 69 / 126

Structs and Interfaces Exercise Session 3 I Exercise Template: exercises/twodobject Implement a new type RightTriangle. Implement all the methods for TwoDObject and use a value receiver (either just save c or compute it from a and b). F. Wenzelmann Introduction to Go August 1, 2017 70 / 126

Structs and Interfaces Exercise Session 3 II Exercise Template: exercises/bintree Implement a type BinTree that implements a binary search tree and stores values of type int. Implement the following methods: NewBinTree ( ) BinTree Add ( elem i n t ) C o n t a i n s ( elem i n t ) b o o l F. Wenzelmann Introduction to Go August 1, 2017 71 / 126

Structs and Interfaces Errors I Go doesn t use try / catch exception handling Instead functions that could encounter errors use multiple return values Usually one of this return values is of type error: t y p e e r r o r i n t e r f a c e { E r r o r ( ) s t r i n g F. Wenzelmann Introduction to Go August 1, 2017 72 / 126

Structs and Interfaces Errors II New errors can be created with the package errors: e := e r r o r s. New( This i s an e r r o r ) Or if formatting is needed with the fmt package: e := fmt. E r r o r f ( I n d e x out o f bounds : %d, i ) Or of course you can create your own error type and implement the interface F. Wenzelmann Introduction to Go August 1, 2017 73 / 126

Structs and Interfaces Error Example I f u n c P a r s e I n t ( s t r s t r i n g ) { v a l, e r r := s t r c o n v. A t o i ( s t r ) i f e r r!= n i l { fmt. P r i n t l n ( E r r o r :, e r r ) e l s e { fmt. P r i n t l n ( Value i s, v a l ) f u n c main ( ) { P a r s e I n t ( 42 ) P a r s e I n t ( 4a ) Playground: https://play.golang.org/p/cyf5rwxgpr F. Wenzelmann Introduction to Go August 1, 2017 74 / 126

Structs and Interfaces Error Example II There is also a special syntax for if statements that is used often in this context: f u n c P a r s e I n t ( s t r s t r i n g ) { i f v a l, e r r := s t r c o n v. A t o i ( s t r ) ; e r r!= n i l { fmt. P r i n t l n ( E r r o r :, e r r ) e l s e { fmt. P r i n t l n ( Value i s, v a l ) f u n c main ( ) { P a r s e I n t ( 42 ) P a r s e I n t ( 4a ) Playground: https://play.golang.org/p/s_4cnyyy8s F. Wenzelmann Introduction to Go August 1, 2017 75 / 126

Structs and Interfaces Type Assertions I If you want to know which concrete type an interface value has you can perform a type check For example you may have a type that implements error and do something specific if a certain type is returned Note: This is not the normal way to do this in Go... F. Wenzelmann Introduction to Go August 1, 2017 76 / 126

Structs and Interfaces Type Assertions II t y p e A c c e s s D e n i e d E r r o r s t r u c t { protectedname s t r i n g f u n c ( e A c c e s s D e n i e d E r r o r ) E r r o r ( ) s t r i n g { r e t u r n fmt. S p r i n t f ( A c c e s s to %s d e n i e d, e. protectedname ) f u n c E v a l E r r ( e r r e r r o r ) { i f e r r == n i l { r e t u r n i f a c c e s s E r r, ok := e r r. ( A c c e s s D e n i e d E r r o r ) ; ok { fmt. P r i n t l n ( E v i l! C a l l i n g 9 1 1 :, a c c e s s E r r ) e l s e { fmt. P r i n t l n ( e r r ) Playground: https://play.golang.org/p/qyasdgtbgy F. Wenzelmann Introduction to Go August 1, 2017 77 / 126

Structs and Interfaces Type Assertions III Can also be used in switch: f u n c P r e t t y ( a n y t h i n g i n t e r f a c e {) { s w i t c h v := a n y t h i n g. ( t y p e ) { c a s e i n t : fmt. P r i n t l n ( I n t :, v ) c a s e f l o a t 6 4, f l o a t 3 2 : fmt. P r i n t f ( F l o a t : %.2 f \n, v ) c a s e R e c t a n g l e : fmt. P r i n t f ( R e c t a n g l e : Width = %.2 f, Height = %.2 f \n, v. Width, v. Height ) d e f a u l t : fmt. P r i n t l n ( Something e l s e :, a n y t h i n g ) Playground: https://play.golang.org/p/l7tt7awjup F. Wenzelmann Introduction to Go August 1, 2017 78 / 126

Structs and Interfaces Reading a File and the defer Statement I The defer statement is used to defer the execution of function call until the surrounding function returns In the following example we show how to read a file line by line Golang has an interface called io.reader, see GoDoc It has a single function: t y p e Reader i n t e r f a c e { Read ( p [ ] b y t e ) ( n i n t, e r r e r r o r ) Which reads up to len(p) bytes into p and returns the number of bytes read Often you don t read directly from a Reader but use a bufio.reader or bufio.scanner F. Wenzelmann Introduction to Go August 1, 2017 79 / 126

Structs and Interfaces Reading a File and the defer Statement II f u n c main ( ) { f, e r r := os. Open ( t e s t. t x t ) i f e r r!= n i l { fmt. P r i n t l n ( E r r o r opening f i l e :, e r r ) os. E x i t ( 1 ) d e f e r f. C l o s e ( ) s c a n n e r := b u f i o. NewScanner ( f ) f o r s c a n n e r. Scan ( ) { fmt. P r i n t l n ( s c a n n e r. Text ( ) ) i f e r r = s c a n n e r. E r r ( ) ; e r r!= n i l { fmt. P r i n t l n ( E r r o r w h i l e r e a d i n g f i l e :, e r r ) os. E x i t ( 1 ) F. Wenzelmann Introduction to Go August 1, 2017 80 / 126

Structs and Interfaces Reading a File and the defer Statement III In the above example we first opened the file with os.open(...) Once sucessfully opened we defer the call to the Close function, that s to say we wait until the surrounding function finishes and then close the file We create a bufio.scanner, by default this will scan for line breaks, but you may set a different split function See GoDoc Note You can use multiple defer statements, even with the same variable name. The deferred call s arguments are evaluated immediately. But the function call is not executed until the surrounding function returns! a a https://tour.golang.org/flowcontrol/12 F. Wenzelmann Introduction to Go August 1, 2017 81 / 126

Structs and Interfaces Reading a File and the defer Statement IV There is also a mechanism called panic and recover We will not discuss it here, here s some reading: https://blog.golang.org/defer-panic-and-recover F. Wenzelmann Introduction to Go August 1, 2017 82 / 126

Concurrency in Go What is Concurrency Wikipedia Concurrent computing is a form of computing in which several computations are executed during overlapping time periods concurrently instead of sequentially (one completing before the next starts). Source: https://en.wikipedia.org/wiki/concurrent_computing We may think of it as many things happening simultaneously Many languages and models today are not very good at expressing this view F. Wenzelmann Introduction to Go August 1, 2017 83 / 126

Concurrency in Go The go Statement Go is most popular for its mechanism for concurrent programming, it s very easy to write concurrent programs in Go It provides the go statement for running things concurrently And it also has an easy way to communicate between things happening concurrently Go was strongly influenced by the paper Communicating Sequential Processes by C. A. R. Hoare, first published 1985 Electronic version: http://www.usingcsp.com/cspbook.pdf Further reading on the Go blog: https://blog.golang.org/share-memory-by-communicating Don t confuse concurrency and parallelism! F. Wenzelmann Introduction to Go August 1, 2017 84 / 126

Concurrency in Go Concurrency vs. Parallelism In what follows there are some quotes from Rob Pike s wonderful video Concurrency Is Not Parallelism : https://youtu.be/cn_dpybzkso Concurrency is a way of thinking and designing / structuring software The goal of concurrency is a good structure (Concurrency) Is the execution of independently executing processes Parallelism on the other hand is the simultaneous execution of multiple things, possibly related, possibly not Dealing with a lot of things at once, vs doing a lot of things at once But often parallelism helps you because things run faster (they don t have to) when you execute concurrent Go programs F. Wenzelmann Introduction to Go August 1, 2017 85 / 126

Concurrency in Go The go Statement - A Simple Example I The go statement starts a new goroutine and runs it concurrently It s as simple as this: Use go f(args) to run something concurrent, you don t wait for the routine to finish, you just start it and it does something for you A pretty easy example: f u n c main ( ) { go f u n c ( ) { f o r i := 0 ; i < 1 0 ; i++ { fmt. P r i n t l n ( i ) ( ) Playground: https://play.golang.org/p/zepoa66kjm F. Wenzelmann Introduction to Go August 1, 2017 86 / 126

Concurrency in Go The go Statement - A Simple Example II If you run the program, what happens? You ll probably see nothing, as mentioned before a new goroutine starts, the current goroutine will not wait for another one to finish! Add time.sleep() and we should see something f u n c main ( ) { go f u n c ( ) { f o r i := 0 ; i < 1 0 ; i++ { fmt. P r i n t l n ( i ) ( ) time. S l e e p (2 time. Second ) Playground: https://play.golang.org/p/dmddlxe30y F. Wenzelmann Introduction to Go August 1, 2017 87 / 126

Concurrency in Go The go Statement - A Simple Example III Of course using time.sleep is no proper way to wait for a goroutine to finish We need a way to communicate But first look at another simple example where we start multiple goroutines at once F. Wenzelmann Introduction to Go August 1, 2017 88 / 126

Concurrency in Go The go Statement - A Simple Example IV package main import ( fmt time ) f u n c main ( ) { f o r i := 0 ; i < 1 0 ; i++ { go f u n c ( v a l i n t ) { fmt. P r i n t l n ( v a l ) ( i ) time. S l e e p (2 time. Second ) Let s try it local, not in the Playground F. Wenzelmann Introduction to Go August 1, 2017 89 / 126

Concurrency in Go The go Statement - A Simple Example V You don t know in which order the goroutines are executed, so you get a more or less random sequence of outputs You can think of a goroutine as a lightweight thread, but it is not a thread as in other programming languages! Go will internally take care of everything, starting multiple threads on your OS for example goroutines are cheap. Of course they prodocue some overhead, but starting them is not very expensive. You can start even tens of thousands of such goroutines F. Wenzelmann Introduction to Go August 1, 2017 90 / 126

Concurrency in Go The go Statement - A Simple Example VI Why did we pass i as an argument to the function we started as a goroutine? If you don t pass an argument the functions uses i from the closure, but this closure is the same for all goroutines! This is a common mistake, you should always pass an argument to functions you start in a different goroutine inside a loop F. Wenzelmann Introduction to Go August 1, 2017 91 / 126

Concurrency in Go Introduction to Channels The most basic type for communicating between different goroutines are channels Think of them as conduits or assembly belts You can put an element of a certain type on the channel and receive an element from a channel They re safe for concurrent use, so many goroutines may write and read to / from a channel Go principle Do not communicate by sharing memory; instead, share memory by communicating. F. Wenzelmann Introduction to Go August 1, 2017 92 / 126

Concurrency in Go Unbuffered Channels I Create an (unbuffered) channel with make: c := make ( chan i n t ) This creates a channel in which you can write integer values For writing and receiving values there is the operator <- Write to channel: ch < 1 Read from channel: v := < ch F. Wenzelmann Introduction to Go August 1, 2017 93 / 126

Concurrency in Go Unbuffered Channels II f u n c main ( ) { ch := make ( chan i n t ) go f u n c ( ) { ch < 1 ( ) v := < ch fmt. P r i n t l n ( v ) Playground: https://play.golang.org/p/m0zdjegpvc Why is the write operation in a goroutine? Otherwise you get an error like fatal error: all goroutines are asleep - deadlock! This is because channels block F. Wenzelmann Introduction to Go August 1, 2017 94 / 126

Concurrency in Go Unbuffered Channels III The write operation blocks until the value is received by a read to that channel The read operation blocks until it reads a value from the channel This way you can synchronize goroutines I.e. they have to wait for each other to finish That leads to a simple pattern in Go: One goroutine waits for a read and one goroutine writes to that channel once it s finished F. Wenzelmann Introduction to Go August 1, 2017 95 / 126

Concurrency in Go Unbuffered Channels IV f u n c main ( ) { done := make ( chan b o o l ) // s t a r t a go r o u t i n e go f u n c ( ) { f o r i := 0 ; i < 1 0 ; i++ { fmt. P r i n t l n ( i ) // once done w r i t e to c h a n n e l done < t r u e ( ) // w a i t u n t i l g o r o u t i n e i s done < done Playground: https://play.golang.org/p/ojrwrt_cxn F. Wenzelmann Introduction to Go August 1, 2017 96 / 126

Concurrency in Go Unbuffered Channels V After we start the goroutine we read from a channel - so the main goroutine blocks until a value on the channel appears The gouroutine first does some stuff and then informs the channel that it s done Let s look at a more complex example F. Wenzelmann Introduction to Go August 1, 2017 97 / 126

Concurrency in Go Computing the Minimum from a Slice of Ints I We want to compute the minimum from a slice of int values We will make some simplification and assume that the slice contains some elements Sequential approach: f u n c S l i c e M i n ( s [ ] i n t ) i n t { min := s [ 0 ] f o r, v := range s [ 1 : ] { i f v < min { min = v r e t u r n min F. Wenzelmann Introduction to Go August 1, 2017 98 / 126

Concurrency in Go Computing the Minimum from a Slice of Ints II Why don t we cut the slice into smaller pieces and run the method concurrent for all pieces? Use a channel to communicate the result of the concurrent methods F. Wenzelmann Introduction to Go August 1, 2017 99 / 126

Concurrency in Go Computing the Minimum from a Slice of Ints III f u n c main ( ) { s :=... n := l e n ( s ) ch := make ( chan i n t ) // s t a r t to go r o u t i n e s t h a t w r i t e t h e r e s u l t to ch go f u n c ( ) { ch < S l i c e M i n ( s [ : n / 2 ] ) () go f u n c ( ) { ch < S l i c e M i n ( s [ n / 2 : ] ) () res1 := < ch res2 := < ch i f res1 < res2 { fmt. P r i n t l n ( S m a l l e s t v a l u e :, r e s 1 ) e l s e { fmt. P r i n t l n ( S m a l l e s t v a l u e :, r e s 2 ) Playground: https://play.golang.org/p/izpptcz32e F. Wenzelmann Introduction to Go August 1, 2017 100 / 126

Concurrency in Go Does Parallelism Help? In the above example we have the hope that our concurrent approach helps to improve the execution time due to parallelism Another question: Why only use two pieces? Why not split into even more? Parallelism Parallelism may help to improve your runtime, but this does not mean that a concurrent approach is always faster! Gos aim is to provide clear structured code via concurrency, not to improve your runtime using parallelism, but often enough this is the case! F. Wenzelmann Introduction to Go August 1, 2017 101 / 126

Concurrency in Go Buffered Channels Until now we ve only seen unbuffered channels Provide the buffer size as the second argument to make to create an unbuffered channel ch := make ( chan i n t, 10) Sends block only when the buffer is full, reads when the channel is empty Example: Coordinate n workers that work concurrently F. Wenzelmann Introduction to Go August 1, 2017 102 / 126

Concurrency in Go range and Closing Channels I If it is unkown how many arguments you have to read from a channel, you can use range ch to iterate over all its values This reads until the channel gets closed by close(ch) Example: Read values from a search of unkown size You can also close a channel and still retrieve the remaining results F. Wenzelmann Introduction to Go August 1, 2017 103 / 126

Concurrency in Go range and Closing Channels II f u n c main ( ) { ch := make ( chan i n t ) go f u n c ( ) { f o r i := 0 ; i < 1 0 ; i++ { ch < i c l o s e ( ch ) ( ) f o r v a l := range ch { fmt. P r i n t l n ( v a l ) Playground: https://play.golang.org/p/q7nsmq6dur F. Wenzelmann Introduction to Go August 1, 2017 104 / 126

Concurrency in Go Read / Write Channels If you want to signal that a function only reads / writes to a channel you can use the type chan<- string for a channel were strings can be written <-chan string for a channel were strings can be read F. Wenzelmann Introduction to Go August 1, 2017 105 / 126

Concurrency in Go Running Multiple goroutines I Sometimes you need to run multiple goroutines that don t return anything / don t write to a channel In this case you can use a WaitGroup from the sync package F. Wenzelmann Introduction to Go August 1, 2017 106 / 126

Concurrency in Go Running Multiple goroutines II f u n c dosomething ( ) { time. S l e e p ( time. Second 3) f u n c main ( ) { v a r wg sync. WaitGroup wg. Add ( 5 ) f o r i := 0 ; i < 5 ; i++ { go f u n c ( ) { d e f e r wg. Done ( ) dosomething ( ) ( ) wg. Wait ( ) Playground: https://play.golang.org/p/xqltxy0kgr F. Wenzelmann Introduction to Go August 1, 2017 107 / 126

Concurrency in Go Running Multiple goroutines III With wg.add(n) you add n events to wait for After all our go routines are started you use wg.wait(). This operation blocks until the counter reaches zero A call to wg.done() reduces the counter by one If you have to dynmaically Add new values make sure that the counter can t reach zero until you call Add This means usually: calls to Add should execute before the statement creating the goroutine or other event to be waited for F. Wenzelmann Introduction to Go August 1, 2017 108 / 126

Concurrency in Go Running Multiple goroutines IV Make sure to always call wg.done defer is a good way to achieve this Read the doc for more details F. Wenzelmann Introduction to Go August 1, 2017 109 / 126

Concurrency in Go Exercise Session 4 I Exercise Template: exercises/matrix Implement matrix multiplication for two matrices A R n m and B R m k. In the template you ll find an implementation that doesn t use concurrency. Improve this implementation by starting a goroutine for each row in A and in this goroutine starts a new goroutine for each column in B. The main function creates some big matrices and compares the execution time of both implementations. F. Wenzelmann Introduction to Go August 1, 2017 110 / 126

Concurrency in Go Exercise Session 4 II Exercise Template: exercises/bintree Go has no iterator interface. There are two common approaches: 1 Implement a function that writes all values in a channel 2 Implement a function that accepts a function and applies a function to all values in the collection Implement both approaches for your BinTree type. Both versions should iterate the values sorted. I t e r a t e V a l u e s ( ch chan< i n t ) Apply ( f f u n c ( v a l i n t ) ) Implement the following with those methods (choose one or do both) 1 Print all values 2 Build the sum of all values F. Wenzelmann Introduction to Go August 1, 2017 111 / 126

Testing and Benchmarking The package testing The package testing provides method for testing and benchmarking your code For details see the documentation here Put your tests in a different package, i.e. create a directory tests Create files ending in test.go To test function X write a method TestX(t *testing.t) To benchmark function X write a method BenchmarkX(b *testing.b) F. Wenzelmann Introduction to Go August 1, 2017 112 / 126

Testing and Benchmarking Testing and Benchmarking Example I f u n c F a c t o r i a l ( n u i n t ) u i n t { v a r r e s u i n t = 1 v a r i u i n t = 1 f o r ; i <= n ; i++ { r e s = i r e t u r n r e s f u n c F a c t o r i a l R e c ( n u i n t ) u i n t { i f n == 0 { r e t u r n 1 e l s e { r e t u r n n F a c t o r i a l R e c ( n 1) F. Wenzelmann Introduction to Go August 1, 2017 113 / 126

Testing and Benchmarking Testing and Benchmarking Example II f u n c T e s t F a c t o r i a l ( t t e s t i n g.t) { v a l u e s := [ ] u i n t {0, 1, 2, 3 r e s u l t s := [ ] u i n t {1, 1, 2, 6 f o r i := 0 ; i < l e n ( v a l u e s ) ; i++ { f := f a c t o r i a l. F a c t o r i a l ( v a l u e s [ i ] ) i f f!= r e s u l t s [ i ] { t. E r r o r f ( Expected %d! = %d, got %d, v a l u e s [ i ], r e s u l t s [ i ], f ) F. Wenzelmann Introduction to Go August 1, 2017 114 / 126

Testing and Benchmarking Testing and Benchmarking Example III Change to the directory examples/factorial/tests Run go test: PASS ok golangsrc/examples/factorial/tests 0.001s Add a false entry in the tests and run again: test FAIL: TestFactorial (0.00s) factorial test.go:15: Expected 3! = 7, got 6 FAIL exit status 1 FAIL golangsrc/examples/factorial/tests 0.001s F. Wenzelmann Introduction to Go August 1, 2017 115 / 126

Testing and Benchmarking Testing and Benchmarking Example IV f u n c B e n c h m a r k F a c t o r i a l ( b t e s t i n g. B) { f o r i := 0 ; i < b.n; i++ { f a c t o r i a l. F a c t o r i a l ( 2 0 ) f u n c B e n c h m a r k F a c t o r i a l R e c ( b t e s t i n g. B) { f o r i := 0 ; i < b.n; i++ { f a c t o r i a l. F a c t o r i a l R e c ( 2 0 ) F. Wenzelmann Introduction to Go August 1, 2017 116 / 126

Testing and Benchmarking Testing and Benchmarking Example V Run go test -bench=. BenchmarkFactorial-4 200000000 9.85 ns/op BenchmarkFactorialRec-4 20000000 81.1 ns/op F. Wenzelmann Introduction to Go August 1, 2017 117 / 126

Testing and Benchmarking Further Reading Official documentation https://medium.com/@matryer/ 5-simple-tips-and-tricks-for-writing-unit-tests-in-golang https://smartystreets.com/blog/2015/02/ go-testing-part-1-vanillla F. Wenzelmann Introduction to Go August 1, 2017 118 / 126

Web Programming The Package http The http package provides HTTP client and server implementations Golang is designed for web programming When writing a server each request is handled in its own goroutine We can t discuss everything here, but we ll look at a small example context is a very useful package, but not discussed here F. Wenzelmann Introduction to Go August 1, 2017 119 / 126

Web Programming Further Web Libraries There are connectors for may database types, Go has its own SQL package You require a driver for a certain database type, for example MYSQL, postgres, sqlite,... Also Redis, Memcached,... I haven t found a suitable thing like Django for python But Gorilla offers a lot of stuff CSRF Sessions Secure Cookies... More extensive example: https://golang.org/doc/articles/wiki/ F. Wenzelmann Introduction to Go August 1, 2017 120 / 126

Web Programming Templates Instead of writing your output directly to the ResponseWriter you can use templates This are files in which you can use variables, call functions etc. A bit like Django templates For more details see https://astaxie.gitbooks.io/ build-web-application-with-golang/en/07.4.html and https://golang.org/pkg/html/template/ F. Wenzelmann Introduction to Go August 1, 2017 121 / 126

Organzing Your Go Code Where to Put Your Go Code Usually all your Go code is in one src directory, usually in a directory go in your home Put your own code in a directory github.com/youraccount/yourpackage A package contains multiple source files, each file must have package line package PACKAGENAME You can add subpackages, but for small project this is sufficient Add a cmd directory and a subdirectory for each command For example if you have an executable helloworld, add cmd/helloworld/helloworld.go This file must have package main and a function main() F. Wenzelmann Introduction to Go August 1, 2017 122 / 126

Organzing Your Go Code Function and Struct Names Functions, Interfaces, Structs,... that begin with a capital letter are exported, i.e. can be used in other packages Everything that starts with a lowercase letter can only be used inside your package You should also format your Go code with gofmt helloworld.go or gofmt PACKAGE This shows you how the could should look like, add -w to apply the formatting directly to your file See https://blog.golang.org/go-fmt-your-code Plugins for Go are available for popular editors like vim, Atom,... F. Wenzelmann Introduction to Go August 1, 2017 123 / 126

Organzing Your Go Code Installing Third Party Packages Use go get github.com/..., for example to install the MySQL driver: gogetgithub.com/go-sql-driver/mysql Use go install github.com/... to also compile the main files See https://golang.org/doc/articles/go_command.html F. Wenzelmann Introduction to Go August 1, 2017 124 / 126

Organzing Your Go Code Documenting Your Code Document each function / struct / interface with a comment starting with the name: // HelloWorld p r i n t s H e l l o World to the s t a n d a r d output f u n c HelloWorld ( ) { fmt. P r i n t l n ( H e l l o World ) If you upload your code to github.com your documentation can be found on godoc.org You can also run godoc locally: godoc -http=:6060 and then visit http://localhost:6060/pkg/ F. Wenzelmann Introduction to Go August 1, 2017 125 / 126

The End Thanks for Listening! Do you have any questions or feedback? F. Wenzelmann Introduction to Go August 1, 2017 126 / 126