Let s Go! Akim D le, Etienne Renault, Roland Levillain. June 8, TYLA Let s Go! June 8, / 58

Similar documents
Go Forth and Code. Jonathan Gertig. CSC 415: Programing Languages. Dr. Lyle

Go Cheat Sheet. Operators. Go in a Nutshell. Declarations. Basic Syntax. Hello World. Functions. Comparison. Arithmetic. Credits


GO IDIOMATIC CONVENTIONS EXPLAINED IN COLOR

developed ~2007 by Robert Griesemer, Rob Pike, Ken Thompson open source

Introduzione a Go e RPC in Go

CSCI-GA Scripting Languages

The Go Programming Language. Frank Roberts

understanding

Go Tutorial. Arjun Roy CSE 223B, Spring 2017

Introduction to the Go Programming Language

Introduce C# as Object Oriented programming language. Explain, tokens,

SWIFT! init(title: String) { self.title = title } // required initializer w/ named parameter

Go Language September 2016

OCaml Data CMSC 330: Organization of Programming Languages. User Defined Types. Variation: Shapes in Java

THE GO PROGRAMMING LANGUAGE CHARACTERISTICS AND CAPABILITIES

Operating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst

Motivations History Principles Language Gommunity Success stories Conclusion. Let s Go! A brief introduction to Google s new language.

Topics Covered Thus Far CMSC 330: Organization of Programming Languages

Threads and Continuations COS 320, David Walker

GO SHORT INTERVIEW QUESTIONS EXPLAINED IN COLOR

Jython. An introduction by Thinh Le

Go Tutorial. To do. A brief, gentle intro to Go. Next Networking. q Today

CS 430 Spring Mike Lam, Professor. Data Types and Type Checking

GO MOCK TEST GO MOCK TEST I

CMSC 330: Organization of Programming Languages

Go vs. Swift: The Languages of The Modern Tech Giants

Chapter 1 GETTING STARTED. SYS-ED/ Computer Education Techniques, Inc.

Dialects of ML. CMSC 330: Organization of Programming Languages. Dialects of ML (cont.) Features of ML. Functional Languages. Features of ML (cont.

Pace University. Fundamental Concepts of CS121 1

CS558 Programming Languages

Introduction to Programming Using Java (98-388)

Subprograms. Akim D le Étienne Renault Roland Levillain EPITA École Pour l Informatique et les Techniques Avancées

Topics Covered Thus Far. CMSC 330: Organization of Programming Languages. Language Features Covered Thus Far. Programming Languages Revisited

Don t let data Go astray

Lectures 5-6: Introduction to C

Pierce Ch. 3, 8, 11, 15. Type Systems

Summary of Go Syntax /

Go for Java Developers

CS558 Programming Languages

Symbolic Computation and Common Lisp

Question No: 1 ( Marks: 1 ) - Please choose one One difference LISP and PROLOG is. AI Puzzle Game All f the given

COMP-520 GoLite Tutorial

The Awesomeness of Go. Igor Lankin DevFest Karlsruhe, Nov 2016

Chapter 1 INTRODUCTION SYS-ED/ COMPUTER EDUCATION TECHNIQUES, INC.

A Fast Review of C Essentials Part I

A brief introduction to C programming for Java programmers

Introduction to ML. Mooly Sagiv. Cornell CS 3110 Data Structures and Functional Programming

CS201 - Introduction to Programming Glossary By

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

Software Engineering using Formal Methods

Rheinisch-Westfälische Technische Hochschule Aachen. Lehrstuhl für Datenmanagement und -exploration Prof. Dr. T. Seidl. Proseminar.

CS558 Programming Languages

CPL 2016, week 10. Clojure functional core. Oleg Batrashev. April 11, Institute of Computer Science, Tartu, Estonia

CS 5523 Operating Systems: Midterm II - reivew Instructor: Dr. Tongping Liu Department Computer Science The University of Texas at San Antonio

Test 1 Summer 2014 Multiple Choice. Write your answer to the LEFT of each problem. 5 points each 1. Preprocessor macros are associated with: A. C B.

Processes. Johan Montelius KTH

CS 11 java track: lecture 1

Index. object lifetimes, and ownership, use after change by an alias errors, use after drop errors, BTreeMap, 309

Topic 1: Introduction

Lecture Overview Methods and Interfaces Methods review Interfaces Example: using the sort interface Anonymous fields in structs

Parsing Scheme (+ (* 2 3) 1) * 1

A process. the stack

CS11 Java. Fall Lecture 1

Short Notes of CS201

CMSC 330: Organization of Programming Languages. OCaml Imperative Programming

low and not larger than high. 18 points

Distributed Systems. 02r. Go Programming. Paul Krzyzanowski. TA: Yuanzhen Gu. Rutgers University. Fall 2015

Programming with Math and Logic

Formal Specification and Verification

Go Circuit: Distributing the Go Language and Runtime. Petar Maymounkov

Review&Preview 1/23/15, 4:08:07 PM 1. 3rd edition - standardized, and standard library allows programmer to start from a higher level

TYPES, VALUES AND DECLARATIONS

New Parallel Programming Languages for Optimization Research

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor

CS 231 Data Structures and Algorithms, Fall 2016

Software Engineering using Formal Methods

Advanced use of the C language

D7020E. The dynamic evolution of a system Robust and Energy-Efficient Real-Time Systems. blocked Lecture 2: Components & the Timber language.

D7020E. Robust and Energy-Efficient Real-Time Systems D7020E. Lecture 2: Components & the Timber language

Using the Go Programming Language in Practice

C Introduction. Comparison w/ Java, Memory Model, and Pointers

1. true / false By a compiler we mean a program that translates to code that will run natively on some machine.

Scala : an LLVM-targeted Scala compiler

G Programming Languages Spring 2010 Lecture 6. Robert Grimm, New York University

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

Erlang and Go (CS262a, Berkeley Fall 2016) Philipp Moritz

Topic 6: A Quick Intro To C

CMSC 330: Organization of Programming Languages. Ownership, References, and Lifetimes in Rust

CMSC330. Objects, Functional Programming, and lambda calculus

Type Systems, Type Inference, and Polymorphism

Introduction to programming with Python

Concurrency, Thread. Dongkun Shin, SKKU

GOLD Language Reference Manual

Functional Programming. Introduction To Cool

COMP 181. Agenda. Midterm topics. Today: type checking. Purpose of types. Type errors. Type checking

Low-Level Programming in C

Design Issues. Subroutines and Control Abstraction. Subroutines and Control Abstraction. CSC 4101: Programming Languages 1. Textbook, Chapter 8

THE CONCEPT OF OBJECT

Shared Channels etc.

Transcription:

Let s Go! Akim Demaille, Etienne Renault, Roland Levillain June 8, 2017 TYLA Let s Go! June 8, 2017 1 / 58

Table of contents 1 Overview 2 Language Syntax 3 Closure 4 Typed functional programming and Polymorphism 5 Co-routines 6 Even More Features TYLA Let s Go! June 8, 2017 2 / 58

Go (also referred as Golang) First appeared in November 2009 TYLA Let s Go! June 8, 2017 3 / 58

Go (also referred as Golang) First appeared in November 2009 Some Unix/C-stars: TYLA Let s Go! June 8, 2017 3 / 58

Go (also referred as Golang) First appeared in November 2009 Some Unix/C-stars: Ken Thompson (Multics, Unix, B, Plan 9, ed, UTF-8, etc. Turing Award) TYLA Let s Go! June 8, 2017 3 / 58

Go (also referred as Golang) First appeared in November 2009 Some Unix/C-stars: Ken Thompson (Multics, Unix, B, Plan 9, ed, UTF-8, etc. Turing Award) Rob Pike (Plan 9, Inferno, Limbo, UTF-8, Squeak, etc.) TYLA Let s Go! June 8, 2017 3 / 58

Go (also referred as Golang) First appeared in November 2009 Some Unix/C-stars: Ken Thompson (Multics, Unix, B, Plan 9, ed, UTF-8, etc. Turing Award) Rob Pike (Plan 9, Inferno, Limbo, UTF-8, Squeak, etc.) Russ Cox (Plan 9, R2E etc.) TYLA Let s Go! June 8, 2017 3 / 58

Go (also referred as Golang) First appeared in November 2009 Some Unix/C-stars: Ken Thompson (Multics, Unix, B, Plan 9, ed, UTF-8, etc. Turing Award) Rob Pike (Plan 9, Inferno, Limbo, UTF-8, Squeak, etc.) Russ Cox (Plan 9, R2E etc.) Derived from C and Pascal TYLA Let s Go! June 8, 2017 3 / 58

Go (also referred as Golang) First appeared in November 2009 Some Unix/C-stars: Ken Thompson (Multics, Unix, B, Plan 9, ed, UTF-8, etc. Turing Award) Rob Pike (Plan 9, Inferno, Limbo, UTF-8, Squeak, etc.) Russ Cox (Plan 9, R2E etc.) Derived from C and Pascal Open-source TYLA Let s Go! June 8, 2017 3 / 58

Go (also referred as Golang) First appeared in November 2009 Some Unix/C-stars: Ken Thompson (Multics, Unix, B, Plan 9, ed, UTF-8, etc. Turing Award) Rob Pike (Plan 9, Inferno, Limbo, UTF-8, Squeak, etc.) Russ Cox (Plan 9, R2E etc.) Derived from C and Pascal Open-source Garbage Collected, compiled, CSP-style concurrent programming Go is an attempt to combine the safety and performance of statically typed languages with the convenience and fun of dynamically typed interpretative languages. [Rob Pike] TYLA Let s Go! June 8, 2017 3 / 58

Some compagnies using Go Google CoreOS Dropbox Netflix MongoDB SoundMusic Uber Twitter Dell Docker Github Intel Lyft... TYLA Let s Go! June 8, 2017 4 / 58

Table of contents 1 Overview 2 Language Syntax 3 Closure 4 Typed functional programming and Polymorphism 5 Co-routines 6 Even More Features TYLA Let s Go! June 8, 2017 5 / 58

Hello World package main import ( " fmt " "os" ) func main () { fmt. Println (" Hello ", os. Args [1]) Compile and run with: go run hello.go yournamehere TYLA Let s Go! June 8, 2017 6 / 58

Hello World package main import ( " fmt " "os" ) func main () { fmt. Println (" Hello ", os. Args [1]) Compile and run with: go run hello.go yournamehere Documentation: godoc -http= :6060 http://localhost:6060/pkg/ TYLA Let s Go! June 8, 2017 6 / 58

Packages Every Go program is made up of packages. Programs start running in package main package main import " fmt " import " math / rand " func main () { fmt. Println ("My favorite number is", rand. Intn (10)) TYLA Let s Go! June 8, 2017 7 / 58

Exported Names Every name that begins with a capital letter is exported unexported names are not accessible from outside the package package main import " fmt " import " math " func main () { fmt. Println ( math.pi) TYLA Let s Go! June 8, 2017 8 / 58

Declaring variables Types come after the name Variables are introduced via var A var declaration can include initializers = Implicit type declaration can be done using := package main import " fmt " func main () { var i = 51 j := 42 var k int = 51 l, m := 12, 18 var n, o int = 12, 18 fmt. Println (i, j, k, l, m, n, o) TYLA Let s Go! June 8, 2017 9 / 58

Functions A function can take zero or more arguments The return type comes after the declaration, and before the body Shared types can be omitted from all but the last parameter A function can return any number of results func add1 ( x int, y int ) int { return x + y func add2 (x, y int ) int { return x + y func swap (x, y string ) ( string, string ) { return y, x TYLA Let s Go! June 8, 2017 10 / 58

Named return values return values may be named names should be used to document the meaning of the return value A return statement without arguments returns the named return values. This is called naked returns. Naked return statements should be used only in short functions. package main import " fmt " func split ( input int ) (x, y int ) { x = input * 4 / 9 y = input - x return func main () { fmt. Println ( split (42)) TYLA Let s Go! June 8, 2017 11 / 58

Types bool string int int8 int16 int32 int64 uint uint8 uint16 uint32 uint64 uintptr byte rune float32 float64 complex64 complex128 Variables declared without an explicit initial value are given their zero value (for string, for bool false,...) The expression T(v) converts the value v to the type T func main () { var i int = 42 var f float64 = float64 ( i) var b bool var s string fmt. Printf ("%v %v %v %q\n", i, f, b, s) TYLA Let s Go! June 8, 2017 12 / 58

Constants Numeric constants are high-precision values. An untyped constant takes the type needed by its context. Constants, like imports, can be grouped. package main import " fmt " const ( Big = 1 << 100 Small = Big >> 99 ) func main () { fmt. Println ( Small ) fmt. Println ( Small *2.01) TYLA Let s Go! June 8, 2017 13 / 58

For init;condition; loop { body No parentheses surrounding the three components of the for statement The braces are always required. The loop will stop iterating once the boolean condition evaluates to false. The init and post statement are optional (while loop) Omit the loop condition to get a forever loop package main import " fmt " func main () { sum := 6 for i := 0; i < 9; i ++ { sum += i fmt. Println ( sum ) TYLA Let s Go! June 8, 2017 14 / 58

Conditional testing Variables declared by the statement are only in scope until the end of the if No parentheses surrounding the declaration plus the condition package main import " fmt " func main () { if v := 42; v < 51 { fmt. Println (v) else { fmt. Println (" Ohoh ") TYLA Let s Go! June 8, 2017 15 / 58

Switch A case body breaks automatically, unless it ends with a fallthrough statement Switch cases evaluate cases from top to bottom, stopping when a case succeeds. Switch without a condition is the same as switch true package main ; import ( " fmt "; " runtime " ) func test () string { return " myos " func main () { fmt. Print ("Go runs on ") switch os := runtime. GOOS ; os { case " darwin ": fmt. Println (" MacOS.") case test (): fmt. Println ("My OS") case " linux ": fmt. Println (" GNU / Linux.") default : fmt. Printf ("%s.", os) TYLA Let s Go! June 8, 2017 16 / 58

Pointers * allows dereferences & generates a pointer to its operand No pointer arithmetic package main import " fmt " func main () { var i int = 21 var p* int = &i fmt. Println (*p) *p = *p + 2 fmt. Println (i) TYLA Let s Go! June 8, 2017 17 / 58

Structures Struct fields are accessed using a dot Struct fields can be accessed through a struct pointer (*p).x or p.x package main import " fmt " type FooBar struct { X int Y int func main () { v := FooBar {1, 2 v.x = 4 fmt. Println (v.x) p := &v p.x = 18 fmt. Println (v.x) TYLA Let s Go! June 8, 2017 18 / 58

Anonymous Structures Structs can be anonymous Structs can be raw compared package main import " fmt " func main () { a := struct { i int b bool {51, false b := struct { i int b bool {51, false fmt. Println (a == b) TYLA Let s Go! June 8, 2017 19 / 58

Arrays An array has a fixed size A slice, on the other hand, is a dynamically-sized, flexible view into the elements of an array Slices are like references to arrays Lower and/or upper bounds can be omitted for slices Slices can be increased/decrease. Use len or cap to know length or capacity of a slice. package main import " fmt " func main () { primes := [/* size */]int {2, 3, 5, 7, 11, 13 var s [] int = primes [ 1: 4] fmt. Println (s) var s2 [] int = primes [: 4] fmt. Println (s2) TYLA Let s Go! June 8, 2017 20 / 58

Dynamic Arrays Dynamic arrays are built over slices May ise the built-in make function to specify length and capacity Use append to add new elements package main import " fmt " func main () { d := make ([] int, 0/* length */, 0 /* capacity */) // Previous equivalent to d := [] int { d = append (d, 42, 51) fmt. Printf ("%s len =%d cap =%d %v\n", "d", len (d), cap (d), d) TYLA Let s Go! June 8, 2017 21 / 58

Range Iteration over arrays can be done using Range Range provides two values at each iteration: the index a reference toward the element at that index. Skip the index or value by assigning it to package main import " fmt " var array = [] int {1, 2, 4, 8, 16, 32, 64, 128 func main () { for i, v := range array { fmt. Printf ("%d = %d\n", i, v) TYLA Let s Go! June 8, 2017 22 / 58

Map make function returns a map of the given type, initialized and ready for use. The zero value of a map is nil A nil map has no keys, nor can keys be added Test that a key is present with a two-value assignment package main ; import " fmt " var m map [ string ] int func main () { m = make ( map [ string ] int ) m[" EPITA "] = 42 fmt. Print (m[" EPITA "]) delete (m, " EPITA ") elem, ok := m[" EPITA "] fmt. Print (elem, ok) // 42 0 false TYLA Let s Go! June 8, 2017 23 / 58

Package Debug Package debug contains facilities for programs to debug themselves while they are running. func FreeOSMemory(): force Garbage Collection func PrintStack(): print stack func ReadGCStats(stats *GCStats): grab stats on Garbage collection func SetMaxStack(bytes int) int: set maximum stack size func SetMaxThreads(threads int) int: fix maximum number of threads... TYLA Let s Go! June 8, 2017 24 / 58

Table of contents 1 Overview 2 Language Syntax 3 Closure 4 Typed functional programming and Polymorphism 5 Co-routines 6 Even More Features TYLA Let s Go! June 8, 2017 25 / 58

A word on fonctionnal programming Functional programming (FP) has two related characteristics: First-class functions. Functions/methods are first-class citizens, i.e. they can be: TYLA Let s Go! June 8, 2017 26 / 58

A word on fonctionnal programming Functional programming (FP) has two related characteristics: First-class functions. Functions/methods are first-class citizens, i.e. they can be: 1 named by a variable TYLA Let s Go! June 8, 2017 26 / 58

A word on fonctionnal programming Functional programming (FP) has two related characteristics: First-class functions. Functions/methods are first-class citizens, i.e. they can be: 1 named by a variable 2 passed to a function as an argument TYLA Let s Go! June 8, 2017 26 / 58

A word on fonctionnal programming Functional programming (FP) has two related characteristics: First-class functions. Functions/methods are first-class citizens, i.e. they can be: 1 named by a variable 2 passed to a function as an argument 3 returned from a function as a result TYLA Let s Go! June 8, 2017 26 / 58

A word on fonctionnal programming Functional programming (FP) has two related characteristics: First-class functions. Functions/methods are first-class citizens, i.e. they can be: 1 named by a variable 2 passed to a function as an argument 3 returned from a function as a result 4 stored in any kind of data structure. TYLA Let s Go! June 8, 2017 26 / 58

A word on fonctionnal programming Functional programming (FP) has two related characteristics: First-class functions. Functions/methods are first-class citizens, i.e. they can be: 1 named by a variable 2 passed to a function as an argument 3 returned from a function as a result 4 stored in any kind of data structure. Closure. Function/method definitions are associated to some/all of the environment when they are defined. TYLA Let s Go! June 8, 2017 26 / 58

Go Functions are 1st Class Functions can be declared at any levels Functions can be passed as arguments/return of functions package main ; import " fmt " func compute ( fn func ( int ) int, value int ) int { return 42* fn( value ) func main () { myfun := func ( x int ) int { myfun2 := func ( y int ) int { return y* y return myfun2 (x) fmt. Print ( myfun (5)) fmt. Print (" ", compute ( myfun, 5)) // 25 1050 TYLA Let s Go! June 8, 2017 27 / 58

Functions closure A closure is a function value that references variables from outside its body. The function is bound to the variables. package main ; import " fmt " func adder () func ( int ) int { sum := 0 return func ( x int ) int { sum += x return sum func main () { cumul := adder () for i := 0; i < 10; i ++ { fmt. Println ( cumul (i)) TYLA Let s Go! June 8, 2017 28 / 58

Closures are Weak in Go Go closures are not as strong as required by pure Fonctionnal Programming package main ; import " fmt " func main () { counter := 0; f1 := func ( x int ) int { counter += x; return counter f2 := func ( y int ) int { counter += y; return counter fmt. Printf (" %d \n", f1 (1)) fmt. Printf (" %d \n", f2 (1)) fmt. Printf (" %d \n", f1 (1)) TYLA Let s Go! June 8, 2017 29 / 58

Table of contents 1 Overview 2 Language Syntax 3 Closure 4 Typed functional programming and Polymorphism 5 Co-routines 6 Even More Features TYLA Let s Go! June 8, 2017 30 / 58

Functions associated to a type 1/3 No classes, but you can define functions on types A function with a special receiver argument package main ; import (" fmt "; " math ") type MyType struct { X, Y float64 func ( v MyType ) Abs () float64 { return math. Sqrt (v.x*v.x + v.y*v.y) func main () { v := MyType {3, 4 fmt. Println (v. Abs ()) TYLA Let s Go! June 8, 2017 31 / 58

Functions associated to a type 2/3 The receiver is passed by copy unless a pointer is passed as receiver You do not need to dereference the receiver in this case package main ; import (" fmt ") type MyType struct { X, Y float64 func (v* MyType ) SetX (x float64 ) { v.x = x func main () { v := MyType {3, 4 v. SetX (18) fmt. Println (v) TYLA Let s Go! June 8, 2017 32 / 58

Functions associated to a type 3/3 We can declare a function on non-struct types Possible, only for function with a receiver whose type is defined in the same package as the function package main import (" fmt ";" math ") type MyFloat float64 func ( f MyFloat ) Abs () float64 { if f < 0 { return float64 (-f) return float64 ( f) func main () { f := MyFloat (- math. Sqrt2 ) fmt. Println (f. Abs ()) TYLA Let s Go! June 8, 2017 33 / 58

Interface An interface type is defined as a set of method signature A value of interface type can hold any value that implements those methods package main ; import " fmt " type Runner interface { Run () int type MyType struct { X int func ( v MyType ) Run () int { return 42 func main () { var a Runner ; v := MyType {3 a = v; fmt. Println (a. Run ()) TYLA Let s Go! June 8, 2017 34 / 58

Stringer Interface Useful to print types type Person struct { Name string Age int func ( p Person ) String () string { return fmt. Sprintf ("%v (%v years )", p.name, p. Age ) //... fmt. Println ( Person {" John Doe ", 42) TYLA Let s Go! June 8, 2017 35 / 58

Runtime Polymorphism package main ; import " fmt " type Runner interface { Run () int type MyType1 struct { X int type MyType2 struct { X, Y int func ( v MyType1 ) Run () int { return 42 func (v MyType2 ) Run () int { return v.x + v.y func run ( v Runner ) int { return v. Run () func main () { v1 := MyType1 {3 v2 := MyType2 {3, 4 fmt. Println (v1.run (), v2.run ()) fmt. Println ( run (v1), run (v2 )) TYLA Let s Go! June 8, 2017 36 / 58

Maximum Polymorphism and Reflection maximum polymorphism through the empty interface: interface { For example, the printing functions in fmt use it Need for some reflection mechanisms, i.e. ways to check at runtime that instances satisfy types, or are associated to functions. For instance, to check that x0 satisfies the interface I x1, ok := x0.(i); (ok is a boolean, and if true, x1 is x0 with type I) TYLA Let s Go! June 8, 2017 37 / 58

Type Dispatch Dynamic Dispatch can easily be done func dispatch ( i interface {) { switch v := i.( type ) { case int : //... case string : //... default : //... TYLA Let s Go! June 8, 2017 38 / 58

Duck Typing Go functional polymorphism is a type-safe realization of duck typing. Implicit Rule: If something can do this, then it can be used here. Opportunistic behavior of the type instances. Dynamic OO languages like CLOS or Groovy include duck typing in a natural way In static languages: duck typing is realized as a structural typing mechanism (instead of nominal in which all type compatibilities should be made explicit see e.g., implements, extends in Java). Duck typing uses mechanisms similar to the one we have with C++ Generic Programming. TYLA Let s Go! June 8, 2017 39 / 58

Go Interfaces and Structuration Levels Go interfaces: A type-safe overloading mechanism where sets of overloaded functions make type instances compatible or not to the available types (interfaces). TYLA Let s Go! June 8, 2017 40 / 58

Go Interfaces and Structuration Levels Go interfaces: A type-safe overloading mechanism where sets of overloaded functions make type instances compatible or not to the available types (interfaces). The effect of an expression like: x.f(..) depends on all the available definitions of F, on the type of x, and on the set of available interfaces where F occurs TYLA Let s Go! June 8, 2017 40 / 58

Go Interfaces and Structuration Levels Go interfaces: A type-safe overloading mechanism where sets of overloaded functions make type instances compatible or not to the available types (interfaces). The effect of an expression like: x.f(..) depends on all the available definitions of F, on the type of x, and on the set of available interfaces where F occurs About the grain of structuration dilemma between the functional and modular levels: Go votes for the functional level, but less than CLOS, a little more than Haskell, and definitely more than Java/C# (where almost every type is implemented as an encapsulating class)... TYLA Let s Go! June 8, 2017 40 / 58

Summary about polymorphism & interface Go interface-based mechanism is not new, neither very powerful.. TYLA Let s Go! June 8, 2017 41 / 58

Summary about polymorphism & interface Go interface-based mechanism is not new, neither very powerful.. Haskell offers type inference with constrained genericity, and inheritance TYLA Let s Go! June 8, 2017 41 / 58

Summary about polymorphism & interface Go interface-based mechanism is not new, neither very powerful.. Haskell offers type inference with constrained genericity, and inheritance Go structural-oriented type system is not new, neither very powerful... TYLA Let s Go! June 8, 2017 41 / 58

Summary about polymorphism & interface Go interface-based mechanism is not new, neither very powerful.. Haskell offers type inference with constrained genericity, and inheritance Go structural-oriented type system is not new, neither very powerful... OCaml offers type and interface inference with constrained genericity, and inheritance TYLA Let s Go! June 8, 2017 41 / 58

Summary about polymorphism & interface In Go, no explicit inheritance mechanism. The closest mechanism: some implicit behavior inheritance through interface unions (called embedding): type Foo interface { F1 () int ; type Bar interface { F2 () int ; type FooBar interface { Foo // inclusion Bar // inclusion Rule If type T is compatible with FooBar, it is compatible with Foo and Bar too TYLA Let s Go! June 8, 2017 42 / 58

Table of contents 1 Overview 2 Language Syntax 3 Closure 4 Typed functional programming and Polymorphism 5 Co-routines 6 Even More Features TYLA Let s Go! June 8, 2017 43 / 58

Concurrency The idea Impose a sharing model where processes do not share anything implictly (see Hoares Communicating Sequential Processes 1978) Motto Do not communicate by sharing memory; instead, share memory by communicating. Objectives Reduce the synchronization problems (sometimes at the expense of performance) TYLA Let s Go! June 8, 2017 44 / 58

Three basic constructs Goroutines are similar to threads, coroutines, processes, (Googlers claimed they are sufficiently different to give them a new name) TYLA Let s Go! June 8, 2017 45 / 58

Three basic constructs Goroutines are similar to threads, coroutines, processes, (Googlers claimed they are sufficiently different to give them a new name) Goroutines are then automatically mapped to the OS host concurrency primitives (e.g. POSIX threads) TYLA Let s Go! June 8, 2017 45 / 58

Three basic constructs Goroutines are similar to threads, coroutines, processes, (Googlers claimed they are sufficiently different to give them a new name) Goroutines are then automatically mapped to the OS host concurrency primitives (e.g. POSIX threads) A goroutine does not return anything (side-effects are needed) TYLA Let s Go! June 8, 2017 45 / 58

Three basic constructs Goroutines are similar to threads, coroutines, processes, (Googlers claimed they are sufficiently different to give them a new name) Goroutines are then automatically mapped to the OS host concurrency primitives (e.g. POSIX threads) A goroutine does not return anything (side-effects are needed) Channels: a typed FIFO-based mechanism to make goroutines communicate and synchronize TYLA Let s Go! June 8, 2017 45 / 58

Three basic constructs Goroutines are similar to threads, coroutines, processes, (Googlers claimed they are sufficiently different to give them a new name) Goroutines are then automatically mapped to the OS host concurrency primitives (e.g. POSIX threads) A goroutine does not return anything (side-effects are needed) Channels: a typed FIFO-based mechanism to make goroutines communicate and synchronize Segmented stacks make co-routines usables TYLA Let s Go! June 8, 2017 45 / 58

Go Routine A goroutine is a lightweight thread managed by the Go runtime starts a new goroutine running go Goroutines run in the same address space access to shared memory must be synchronized (see sync package) package main ; import (" fmt ";" time ") func say ( s string ) { for i := 0; i < 5; i ++ { time. Sleep (100 * time. Millisecond ) fmt. Println (s) func main () { go say (" world ") say (" hello ") TYLA Let s Go! June 8, 2017 46 / 58

Channels 1/3 Channels are a typed conduits Send to channel using ch < 42 Receive from channel using v :=< ch Channels can be buffered: blocking when the buffer is full or empty package main ; import " fmt " func main () { ch := make ( chan int, 2) ch <- 1 ch <- 2 fmt. Println (<-ch) fmt. Println (<-ch) TYLA Let s Go! June 8, 2017 47 / 58

Channels 2/3 A sender can close a channel to indicate that no more values will be sent. Receivers can test whether a channel has been closed v, ok :=< ch Sending on a closed channel will cause a panic. Channels aren t like files; you don t usually need to close them package main ; import " fmt " func compute ( n int, c chan int ) { for i := 0; i < n; i ++ { c <- i close (c) func main () { c := make ( chan int, 10) go compute ( cap (c), c) for i := range c { fmt. Println ( i) TYLA Let s Go! June 8, 2017 48 / 58

Channels 3/3 Select lets a goroutine wait on multiple communication operations func main () { c1 := make ( chan string ); c2 := make ( chan string ) go func () { time. Sleep ( time. Second * 5) c1 <- " one " () go func () { time. Sleep ( time. Second * 5); c2 <- " two " () for i := 0; i < 2; i ++ { select { case msg1 := <- c1: fmt. Println (" received ", msg1 ) case msg2 := <- c2: fmt. Println (" received ", msg2 ) TYLA Let s Go! June 8, 2017 49 / 58

PingPong Time Demo. TYLA Let s Go! June 8, 2017 50 / 58

Table of contents 1 Overview 2 Language Syntax 3 Closure 4 Typed functional programming and Polymorphism 5 Co-routines 6 Even More Features TYLA Let s Go! June 8, 2017 51 / 58

Reflection & Tags 1/2 Reflection is the ability of program to introspect, and modify its own structure and behavior at runtime package main import ( " fmt " " reflect " ) type Foo struct { FirstName string tag_name :" tag 1" LastName string tag_name :" tag 2" Age int tag_name :" tag 3" TYLA Let s Go! June 8, 2017 52 / 58

Reflection & Tags 2/2 fmt. Printf (" Field Name : %s,\t Field Value : %v,\t func (f * Foo ) reflect () { val := reflect. ValueOf (f). Elem () for i := 0; i < val. NumField (); i ++ { valuefield := val. Field (i) typefield := val. Type (). Field (i) tag := typefield. Tag typefield.name, valuefield. Interface (), tag. Get (" tag_name ")) func main () { f := & Foo { FirstName : " John ", LastName : " Doe ", Age : 30 f. reflect () TYLA Let s Go! June 8, 2017 53 / 58

Defer Defers the execution of a function until the surrounding function returns The deferred call s arguments are evaluated immediately but the function call is not executed until the surrounding function returns. Defer is commonly used to simplify functions that perform various clean-up actions (closing file for instance) package main import " fmt " func main () { defer fmt. Println (" world ") fmt. Println (" hello ") TYLA Let s Go! June 8, 2017 54 / 58

Stacking Defer Deferred function calls are pushed onto a stack When a function returns, its deferred calls are executed in last-in-first-out order package main import " fmt " func main () { fmt. Println (" counting ") for i := 0; i < 10; i ++ { defer fmt. Println (i) fmt. Println (" done ") // counting done 9 8 7 6 5 4 3 2 1 0 TYLA Let s Go! June 8, 2017 55 / 58

Panic and Recover 1/2 Panic is a built-in function that stops the ordinary flow of control and begins panicking. Recover is a built-in function that regains control of a panicking goroutine. Recover is only useful inside deferred functions. package main import " fmt " func g(i int ) { fmt. Println (" Enter g.") panic (i) fmt. Println (" Exit g.") TYLA Let s Go! June 8, 2017 56 / 58

Panic and Recover 2/2 func f() { defer func () { if r := recover (); r!= nil { fmt. Println (" Recovered in f", r) () fmt. Println (" Calling g.") g (42) fmt. Println (" Returned normally from g.") func main () { f() fmt. Println (" Returned normally from f.") TYLA Let s Go! June 8, 2017 57 / 58

Pros & Cons Simple and scalable multithreaded and concurrent programming All is type Tooling and API Performance is on the order of C Includes a lot of paradigms Weak type system GC (tricolor concurrent mark-and-sweep algorithm) causes runtime overhead Not thread-safe No generics No shared libraries: can t load Go code at runtime TYLA Let s Go! June 8, 2017 58 / 58