Go Lecture PDF
Go Lecture PDF
Narbel
The Cremis Saturdays, Saison I
University of Bordeaux 1
April 2010
(v.1.01)
1 / 41
A magnicent quartet...:
Microsoft: Windows, Internet Explorer (Gazelle?), Microsoft Oce, Windows Mobile, C#/F#. Sun: Solaris, HotJava, StarOce, SavaJe, Java. Apple: MacOS, Safari, iWork, iPhoneOS, Objective-C. Google: ChromeOS, Chrome, Google Docs, Android, Go.
2 / 41
4 / 41
References about Go
Bibliography about Go is still rather short...: Ocial doc (on golang.org):
The Go Programming Language Specication. Package Documentation (the standard lib doc). A Tutorial for the Go Programming Language. Eective Go : the main text on the ocial site (could be
better...)
8 / 41
Echo Function in Go
package main import ( os f l a g // command l i n e o p t i o n p a r s e r ) v a r omitNewline = flag . Bool ( n , false , no f i n a l const ( Space = Newline = \ n ) newline )
f u n c main ( ) { flag . Parse ( ) // S c a n s t h e a r g l i s t and s e t s up f l a g s var s s t r i n g = f o r i := 0 ; i < flag . NArg ( ) ; i++ { if i > 0 { s += Space } s += flag . Arg ( i ) } i f ! omitNewline { s += Newline } os . Stdout . WriteString ( s ) }
9 / 41
Echo Function in C
int main ( i n t argc , c h a r argv [ ] ) { i n t nflag ; i f (++ argv && ! strcmp ( argv , n ) ) { ++argv ; nflag = 1 ; } else nflag = 0 ; w h i l e ( argv ) { ( v o i d ) printf ( %s , argv ) ; i f (++ argv ) ( v o i d ) putchar ( ) ; } i f ( nflag == 0 ) ( v o i d ) putchar ( \ n ) ; fflush ( stdout ) ; i f ( ferror ( stdout ) ) exit ( 1 ) ; exit ( 0 ) ; }
10 / 41
A language should not in general be compared from its syntax, sugar gadgets, construct peculiarities... (we skip them). And even if Go does not include revolutionary ideas, there are some points worth to be discussed, e.g.:
Polymorphic functions (CLOS-Haskell-like). Typed functional programming. Easy to use multi-threading.
11 / 41
Functions
Basic function header:
f u n c < function name >(< typed args >) < r e t u r n type > {}
For instance:
func f ( i n t i ) ( int , s t r i n g ) { r e t u r n ( i +1) ( s u p e r g e n i a l ) } x , y := f ( 3 ) ;
12 / 41
13 / 41
The argument arg of type T can be used in the body of the function like the other arguments. For instance:
t y p e Point s t r u c t { x , y float64 } f u n c ( p Point ) Norm ( ) float64 { r e t u r n math . Sqrt ( p . x p . x + p . y p . y ) ; } p := Point { 1 , 2 } ; [ . . . ] p . Norm ( ) [ . . . ] ;
Similar syntax to C++/Java: the associated type argument is privileged, as is an object rel. to its methods.
14 / 41
Truc is then a registered type (in fact, a type of types). Rule: Every data type T with associated functions as declared in the interface Truc is compatible with Truc. Every instance of type T is also an instance of type Truc. A type can satisfy more than one interface.
15 / 41
f u n c main ( ) { nuple1 := &T1 { 7 , 2.35 , b l u e b e r r i e s } ; nuple2 := &T2 { 1 , 2 } ; nuple1 . PrintStandard ( ) ; F ( nuple1 ) ; // o u t p u t : 7 2.35 b l u e b e r r i e s F ( nuple2 ) ; // o u t p u t : 1 2 }
16 / 41
17 / 41
Dynamic Selection
18 / 41
19 / 41
Output:
[ 1 1 3 4 5 3 3 3 ]
20 / 41
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. Naively: When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck. 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).
22 / 41
depends on all the available denitions 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 denitely more than Java/C# (where almost every type is implemented as an encapsulating class)...
23 / 41
Other Languages
Go interface-based mechanism is not new, neither very powerful... For instance, Haskell type classes:
c l a s s SmallClass a where f1 : : a > a f2 : : a > Int // s i m i l a r t o a Go i n t e r f a c e
i n s t a n c e SmallClass Char where f1 x = chr ( ( ord x ) + 1 ) f2 = ord i n s t a n c e SmallClass Bool where f1 _ = True f2 True = 1 f2 False = 0
// i m p l e m e n t a t i o n
// a n o t h e r i m p l e m e n t a t i o n
Other Languages
Go structural-oriented type system is not new, neither very powerful... For instance, inferred Ocaml open object types:
# let f x = ( x#f1 1 ) | | ( x#f2 a ) ; ; // v a l f : < f 1 : i n t > b o o l ; // f 2 : c h a r > b o o l ;
. . > > b o o l
OCaml oers type and interface inference with constrained genericity, and inheritance...
25 / 41
Interface Unions
In Go, no explicit inheritance mechanism. The only possibility: some implicit behavior inheritance through interface unions (called embedding):
t y p e Truc1 i n t e r f a c e { F1 ( ) i n t ; } t y p e Truc2 i n t e r f a c e { F2 ( ) i n t ; } t y p e Truc i n t e r f a c e { Truc1 ; // i n c l u s i o n f Truc2 ; // i n c l u s i o n }
Rule: If type T is compatible with Truc, it is compatible with Truc1 and Truc2 too.
26 / 41
Functional Programming
Functional programming (FP) has two related characteristics:
First-class functions. Functions/methods are rst-class citizens, i.e. they can be (0) named by a variable; (1) passed to a function as an argument; (2) returned from a function as a result; (3) stored in any kind of data structure. Closures. Functions/methods denitions are associated to some/all of the environment when they are dened.
When these are available Most of the FP techniques are possible Caveat: Only full closures can ensure pure FP (and in particular, referential transparency).
27 / 41
Output:
Passed : 1100 1005 105 6
28 / 41
Output:
1 2 3 // => no r e f e r e n t i a l transparency !
29 / 41
Concurrence
The idea: to impose a sharing model where processes do not share anything implictly (cf. Hoares CSP). Motto: Do not communicate by sharing memory; instead, share memory by communicating. A consequence: to reduce the synchronization problems (sometimes at the expense of performance). Only two basic constructs:
Goroutines are similar to threads, coroutines, processes, (Google men claimed they are suciently dierent to give them a new name) Channels: a typed FIFO-based mechanism to make goroutines communicate and synchronize.
30 / 41
Goroutines
To spawn a goroutine from a function or an expression, just prex it by go (in Limbo, it was spawn):
go f ( ) go f u n c ( ) { . . . } // c a l l w i t h an anonymous f u n c t i o n go list . Sort ( )
Goroutines are then automatically mapped to the OS host concurrency primitives (e.g. POSIX threads). NB: A goroutine does not return anything (side-eects are needed)
31 / 41
Channels
a v a i l a b l e /
32 / 41
Concurrent Programming
Example of a simple goroutine without any synchronization (NB: recall that a goroutine cannot return a value):
v a r res i n t = 0 ; f u n c comput ( from i n t , to i n t ) i n t { tmp := 0 f o r i := from ; i < to ; i++ { tmp += i } res = tmp } f u n c main ( ) { go comput ( 0 , 1 0 0 0 0 0 0 ) ; time . Sleep ( 1 0 0 0 0 0 0 ) ; fmt . Println ( The r e s u l t : , res ) }
Concurrent Programming
Example of a simple goroutine with synchronization (using anonymous functions is the idiomatic way of calling expressions as a goroutine):
f u n c comput ( from i n t , to i n t ) i n t { tmp := 0 f o r i := from ; i < to ; i++ { tmp += i } r e t u r n tmp } f u n c main ( ) { ch := make ( chan i n t ) go f u n c ( ) { ch < comput ( 0 , 1 0 0 0 0 0 0 ) } ( ) res := < ch // b l o c k e d u n t i l t h e c a l c u l a t i o n fmt . Println ( The r e s u l t : , res ) }
i s done
34 / 41
Concurrent Programming
A producer/consumer agreement:
v a r ch chan i n t = make ( chan i n t ) ; f u n c prod ( ) { counter := 0 ; for { fmt . Println ( p r o d u c e d : , counter ) ch < counter ; counter++ } } f u n c consum ( ) { for { res := < ch ; fmt . Println ( consumed : , res ) ; } } f u n c main ( ) { wait := make ( chan i n t ) go prod ( ) ; go consum ( ) ; < wait // w a i t t o i n f i n i t y . . . }
(inspired from www.cowlark.com)
35 / 41
Declaration example:
ch := make ( chan i n t , 1 0 0 )
36 / 41
Goroutines and FP
Very naturally comes the idea of mixing multi-threading and functional programming (use of anonymous functions). At least two diculties in doing that in Go:
Goroutines do not return any result ( side-eects are needed). Closures are weak.
For instance, the following variation of the preceding example does not work:
f o r i := 0 ; i < NCPU ; i++ { go f u n c ( ) { ch < comput ( i iterat / NCPU , ( i +1) iterat / NCPU ) }() }
A Partial Presentation...
Go has other points of interest which could have been presented and/or more discussed here: Reection. The standard library. Memory management and pointers. Executable building. Error system (e.g., functions panic/recover, package unsafe, etc.),
39 / 41
Next Time...
The subject of the talk will be...: D is a systems programming language. Its focus is on combining the power and high performance of C and C++ with the programmer productivity of modern languages like Ruby and Python.[..!?] The D language is statically typed and compiles directly to machine code. Its multiparadigm, supporting many programming styles: imperative, object oriented, and metaprogramming. Its a member of the C syntax family, and its appearance is very similar to that of C++.[..!?] It adds to the functionality of C++ by also implementing design by contract, unit testing, true modules, garbage collection, rst class arrays, associative arrays, dynamic arrays, array slicing, nested functions, inner classes, closures, anonymous functions, compile time function execution, lazy evaluation and has a reengineered [..!?]
40 / 41
Go Installation
Go is quite easy to install (be careful about the four environment variables GOROOT, GOARCH, GOOS, GOBIN). Fully available for Linux, FreeBSD, Darwin. (NaCl : on its way) (Windows : on its way + partial Cygwin distribution). Needed : Mercurial (the VCS chosen by Go). To make a basic Go program be useful:
Source code le extension is .go. Compilation with 8g object le with extension .8. Linking with 8l exec le 8.out. Replace the above 8s by 6s for 64 bits architectures.
41 / 41