Google Go

7 downloads 50251 Views 414KB Size Report
This paper introduces the imparative programming language Google Go to the reader. The main aspect is ... ming to web server programming. The question the  ...
Rheinisch-Westfälische Technische Hochschule Aachen Lehrstuhl für Datenmanagement und -exploration Prof. Dr. T. Seidl

Proseminar

Google Go illustrated on the basis of Fibonacci numbers Jan Pennekamp

Mai 2012 SS 2012

Betreuung:

Dipl.-Ing. Marwan Hassani

Declaration of Originality The material in this paper has not previously been submitted for a degree in any University, and to the best of my knowledge contains no material previously published or written by another person except where due to acknowledgement is made in the paper itself.

Aachen, the 31st May 2012

Contents List of Source Code

vi

List of Figures & Tables

vii

Abstract

1

1 Introduction 1.1 Development of Google Go . . . . . . . . . . . . . . . . . . . . 1.2 Plattform support . . . . . . . . . . . . . . . . . . . . . . . . .

2 2 4

2 Basics about Go 2.1 Hello World program 2.2 Data types of Go . . 2.3 Control structures . . 2.4 Memory management 2.5 Advanced features . .

5 5 6 6 7 8

3 The 3.1 3.2 3.3

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

Fibonacci numbers in Go, Pascal and Short code of Google Go . . . . . . . . . . Exceptions . . . . . . . . . . . . . . . . . . Multiple return values and assignments . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

Java 9 . . . . . . . . . . . 9 . . . . . . . . . . . 9 . . . . . . . . . . . 11

4 Future and recent changes 4.1 Go at Google . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.2 Active development . . . . . . . . . . . . . . . . . . . . . . . . 4.3 Own evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . Bibliography

12 12 12 13 I

List of Abbreviations

II

Source Files

IV v

List of Source Code 2.1 2.2 2.3 2.4 3.1 3.2 3.3 3.4 1 2 3 4 5 6

Hello World program implemented in Google Go . . . . . . . . Initializing a struct in Google Go . . . . . . . . . . . . . . . . Loops implemented in Google Go with the for command . . . Package import in Google Go extracted from my own example Exception handling in Java . . . . . . . . . . . . . . . . . . . . Exception handling in Google Go . . . . . . . . . . . . . . . . Multiple return values in Google Go . . . . . . . . . . . . . . . Multiple assignments in one call in Google Go . . . . . . . . . Hello world program implemented in Google Go . . . . . . . . Fibonacci Number calculation implemented in Google Go . . . Fibonacci Number calculation implemented in Pascal . . . . . Fibonacci Number calculation implemented in Java . . . . . . Required additional file for the Java program . . . . . . . . . . Required additional file for the Java program . . . . . . . . . .

vi

5 6 7 8 10 10 11 11 IV V VI VII VIII VIII

List of Figures 1.1 1.2

Google Go logo . . . . . . . . . . . . . . . . . . . . . . . . . . Commonly known influences to Google Go . . . . . . . . . . .

2 4

List of Tables 1.1 1.2

Timeline of Go development [4] . . . . . . . . . . . . . . . . . Goals of Google Go and matching decisions . . . . . . . . . . .

3 3

2.1

built-in standard types of Google Go [2] . . . . . . . . . . . .

6

vii

Abstract This paper introduces the imparative programming language Google Go to the reader. The main aspect is why a programmer should use Go. There is an overview about the development and basic features included. On top of that some concepts of Go are illustrated in connection with the Fibonacci numbers and compared to Java and Pascal. As conclusion there is a brief look into the future and a rating of Go.

1

Chapter 1 Introduction Figure 1.1: Google Go logo

1.1 1.1.1

Development of Google Go Developers

Go is developed an open source project by Google. Go development started in September 2007 with the developers Rob Pike, who worked a long time in a Unix-Team, where he developed the Plan 9 operating system [7], and Ken Thompson, who created the first Unix shell in 1971 and created the programming language B [6].

2

1.1. Development of Google Go

1.1.2

3

Timeline

Table 1.1: Timeline of Go development [4] initial design Sep. 2007

1.1.3

public release Nov. 2009

TIOBE award ’09 Jan. 2010

used at Google Go 1 release May 2010 Mar. 2012

Goals

At the moment of its public release Go had many small issues, which made productive usage nearly impossible before May 2010. What were the reasons for developing a new programming language? Over the years computer systems have evolved in an enormous speed on the one hand. Yet no new system programming language was successfully developed on the other. The common used language C is in productive use since 1973. The project members tried to combine the advantages of both, imperative and dynamic programming languages, to create a new language, which is reliable, fast to code and compile. These ideas are expressed in the Go logo as well. 120.000 lines of Go source code compile in under ten seconds on a slow computer [5]. In addition to these goals Go should be used in every possible task, from system programming over mobile application programming to web server programming. The question the developers had in mind was, what would C look like today. As a modern programming language Go supports network and multiprocessor programming natively [1]. Some final design decisions are listed in the Table 1.2 below. Table 1.2: Goals of Google Go and matching decisions Goals Left out Included

Safety + Efficient pointer arithmetic garbage collector

Easy to code inheritance known syntax

Go code should be short and easy to read and write as explained in my own example.

4

1.1.4

Chapter 1. Introduction

Influences

The basic syntax of Go is similar to the syntax of C, but there are influences from both, Java and Pascal as well [8].There are several languages with influence on the presented one, because Rob Pike took part in several projects [7]. The common known languages and its influences to Go are listed in the Figure 1.2. Figure 1.2: Commonly known influences to Google Go

1.2

Plattform support

A Go compiler is officially available for Linux and Mac OS X systems. A Windows version was developed by a community project with a certain delay until Go 1 introduced an official version [4]. There are versions for all three major architectures i386, amd64, and ARM [4].

Chapter 2 Basics about Go 2.1

Hello World program

List of Source Code 2.1: Hello World program implemented in Google Go 1 package main import " fmt " 4 func main () { fmt . Println ( " Hello world " ) 7 }

The hello world program shows the basic syntax of Go. The striking change is that it does not require semicolons after a complete instruction. Only a for-loop needs semicolons in order to define the borders. Apart from that Go requires only one strict rule. The curly brackets need to be written in the same line as the function declaration or the used loop command. There is no special rule for text indent, so Go is plain in terms of formatting. Comments are added the same way they are in C or Java.

5

6

Chapter 2. Basics about Go

2.2

Data types of Go Table 2.1: built-in standard types of Google Go [2] Integer Float Other Boolean

int8, int16, int32, uint8, ... float32, float64 complex64, complex128, string, char, uchar bool

Go has all kinds of built-in types, the size of these types can be given in its declaration. The language also has functions for explicit type conversion, which can be useful in some cases. Google Go is not an object-oriented programming language, but it features structures, which are already known in C or as records in Pascal. The initialization of those types is less code in Go than in any other language [3]. This new concept, seen with structs in Listing 2.2, is working with arrays, sets and maps as well. In addition to that Go supports anonymous types in structs [3]. This way the compiler decides based on the given type in which part of the struct the information has to be written in. List of Source Code 2.2: Initializing a struct in Google Go type example struct { number int name string } 5 ... var ( valueA example = example {1 , " one " } 8 valueB example = example {2 , " two " } ) 2

2.3

Control structures

Like all of its successors Go offers if-else control structures. This and other control structures can be used with all kinds of known comparative operational factors. On top of that Go handles bitwise operations [3]. Paradoxically Go features the GoTo command, which is generally known for making the code unreadable [1]. In comparison to other languages Go features a complex switch command. It is not only working with integers and characters, it is working with all kind of types [4]. This way a long if-else chain can be cleaned up into a switch command. This feature is used in my own code.

2.4. Memory management

7

Another big change compared to earlier languages is that Go does not support while and repeat/do commands. Go only providesfor-loops. The following code in Listing 2.3 shows how to implement these loops in Go. List of Source Code 2.3: Loops implemented in Google Go with the for command // regular for loop for i := 0; i < 10; i ++ { ... } 3 // while loop for ; sum < 1000; { ... } 6 for sum < 1000 { ... } // infinite loop 9 for ; ; { ... } for true { ... } for { ... }

2.4

Memory management

A change compared to C is that pointer in Go are not used to directly change the accessed memory address [3]. This is a decision for security and readableness of the code. Typically pointers are used to mark if a function accesses a variable call-by-value or call-by-reference. Therefore the star in a function declaration in Go can be compared to the keyword VAR in Pascal. This does not mean that all variables are saved in the stack when working with Go. Allocating heap memory works the same way it does in Pascal, by using the command new [3]. To follow Go’s concept there is one step forward compared to Pascal. Not referenced memory will be freed automatically by the garbage collector [4]. Another important feature Go offers will be presented later in connection with my own example in Listing 3.2, it treats the concept of multiple return values and assignments.

8

Chapter 2. Basics about Go

2.5

Advanced features

The package system and import is currently very similar to the one Java provides [8]. There is one exception in Go it is possible to declare a name for the imported package this can be used before an imported command [3]. This is shown in Listing 2.4. List of Source Code 2.4: Package import in Google Go extracted from my own example 1 import ( . " fmt " err " errors " 4 )

At first Google Go did not support any exception or error handling, this was added in a later version of Go [4]. As of today there are regular errors, which do not affect the program’s stability, and panics, which create a run time error after a critical event. Like the Java programming language, Go has an implementation for the interfaces design pattern built-in [3]. Therefore a program can be planned very well between multiple code writers. On top of that Go provides an extra tool, which creates an overview over the current file and its implementations, it is calles godoc [4]. In contrast to Java, Go has not yet implemented a tool for verifying a program’s correctness. Although Go is a young programming language, there are many packages which offer functions on special data types. For example there are maps, linked lists, rings and heaps implemented [4]. Go as well has many mathematical functions in several packages. Over the years these collection will surely grow further.

Chapter 3 The Fibonacci numbers in Go, Pascal and Java 3.1

Short code of Google Go

This example shows the calculation of Fibonacci numbers from 1 to 99 in Google Go, Pascal and Java. All programs feature basic error handling and use an imperative algorithm to calculate the result. The Fibonacci numbers are used to illustrate different aspect in computer sciene and return repeatedly during the study. Both Java and Go have around 35 lines of code, but the Go program uses clearly less characters (707 characters vs. 1020 characters). Nevertheless the Go code is as readable as the Java code. Pascal has only few lines more, but it is missing a real error handling, which both alternatives provide. My intention in this example was to limit the program’s range to calculate the Fibonacci numbers, therefore only Pascal catches wrong inputs. This does not mean that wrong inputs cannot be handled in Java and Go.

3.2

Exceptions

The most sophisticated exception system is built in Java, but this spectrum of features is not possible in Go, because it is not an object-oriented language. As presented in my example Go can throw errors as well and this way the programmer can prevent the program from crashing.

9

10

Chapter 3. The Fibonacci numbers in Go, Pascal and Java List of Source Code 3.1: Exception handling in Java

try { System . out . println ( " The fibonacci number of " + n + " is " + fib ( n ) ) ; } 2 catch ( F i b o n a c c i N e g a t i v e E x c e p t i o n fne ) { System . out . println ( " Number lower / equal zero , try again . " ) ;} catch ( F i b o n a c c i T o o B i g E x c e p t i o n ftbe ) 5 { System . out . println ( " Number higher / equal 100 , try again . " ) ;} public static long fib ( int n ) throws FibonacciNegativeException , F i b o n a c c i T o o B i g E x c e p t i o n { 8 if ( n = 100) 11 throw new F i b o n a c c i T o o B i g E x c e p t i o n () ; ... } List of Source Code 3.2: Exception handling in Google Go 1 switch { case n = 100: return 0 , 1 , err . New ( " Number higher / equal 100 , try again . " ) } 7 ... if err != nil { f . Println ( err ) 10 } else { f . Printf ( " The fibonacci number of % v is % v \ n " ,n , res ) }

Compared to the better known programming languages, this code features two interesting features of Go. First there is the early mentioned use of the complex switch command [4]. The code in Listing 3.2 shows how to write an if-else chain with this new concept. This makes the code more readable and requires less typing as well. In other languages long if-else chains limit the readability and comprehension enormously.

3.3. Multiple return values and assignments

3.3

11

Multiple return values and assignments

The second Go feature that is implemented in my example is the possibility to obtain multiple return values by a function. Surely this is possible by returning a struct or an array as well, but with in Go such a program can be written without much foreknowledge and without complex data types. It is not necessary to declare a special type and the code stays more simple. But why use multiple return values? In this example the program could continue in a form, where the user is asked if he or she wants to calculate a higher Fibonacci number. This way the current calculated number and the index could be transferred to the function and the previous calculation would not have to be repeated. This is not implemented in the presented code to keep it short and comparable to the other. List of Source Code 3.3: Multiple return values in Google Go // function declaration func fib (a , b int64 , n int ) ( int64 , int64 , error ) { 3 // name parameters return values

6

// function call _ , res , err := // return values

fib (0 ,1 , n ) name parameters

This limited example had one advantage as well, leaving out this aspect allowed me to show another feature of Go. The underscore is used when a function returns a value, which is not needed later on at this point of the program [4]. This way the same function can be used in different parts of a program, where different return values matter. Further more there is no memory wasted for not needed values. The Go compiler even stops with an error when this concept is not used in the code. Another small feature of Go which is included in the code is that Go is able to process multiple assignments in one line [3]. This is very convienient when switching the values of two variables. In my example it is used to calculate the Fibonacci numbers iterative. But using more than two assignments in one row, will make the code less readable, as it is already obvious in my example. List of Source Code 3.4: Multiple assignments in one call in Google Go b , a = a +b , b 2 // uses the values of the variables before the call

The Pascal code is attachted at the end of this paper to see the resemblence of the syntax. There is no other programming technique included.

Chapter 4 Future and recent changes 4.1

Go at Google

Google itself uses Go in various projects, the website www.golang.org shows what Go is capable of, because it is written in this new language [4]. In the future there will follow more projects which are based on Google Go. Recently Go developed from a new language with stability issues to a language, which has a real major version for productive use. The mentioned version was released on March 28th 2012 and is called Go 1 [4]. It has no major feature changes, it mostly brings more stability. The purpose of this release is to create a final standard of Go. All following releases should be compatible with this version. Go 1 even includes a tool which brings old Go programs to the new Go 1 standard [4]. Most of these syntax changes affect only some special aspects [4].

4.2

Active development

Go development is very active, there are many aspects which were added after the first release [4]. A better error handling was included after the initial release. More and more the developers are adding functional concepts into Go. The interesting programming techniques form Go into an innovative and interesting language. Higher order functions which are known from Haskell are already supported in the current build of Go [8]. On top of that the developer will add generics to the code at some point [4]. In the past year this was not a priority, because stability was more urgent. A GUI for Go will be provided in the future as well [4]. 12

4.3. Own evaluation

4.3

13

Own evaluation

My personal opinion on Go is that it has chances to become a widely used programming language. It combines the advantages of the most popular languages and creates a simple and fast to write language. Experts in C, Java or Pascal can understand and transfer to Go quickly. Beginners have a simple language with all modern benefits. There is a well maintained wiki on the website [4]. The main reason for learning Go is that the programmer can use it in any project, Go is available for every platform and device [4]. From my point of view there is no reason not to use Go. Every feature Go promises is included and working. With special requirements which are not matched by Go another language might be the better choice, but nearly every program can be implemented with another program design in Go. Some people refuse Go, because it is different and new or because it is supported by Google. Today 25 of 50 core developers are independent and not financed by Google [4]. In May 2012 there have been published three books about Google Go, which all look quite promising and interesting. Before Go 1 it was hard to find much literature, but the ones available showed a nice introduction and an easy transfer to Go. Now Go standard is final [4] and more papers and literature will follow.

Bibliography [1] Ivo Balbaert. The Way to Go - A Thorough Introduction to the Go Programming Language. iUniverse, Antwerp, 2012. Covers the release of Go 1. [2] Rainer Feike. German community site to promote Google Go. May 2012. http://www.gommunity.de/ visited on May 18th 2012. [3] Rainer Feike and Steffen Blass. Programmierung in Google Go. AddisonWesley, München, 2010. [4] Google. The Go Programming Language - offical website. May 2012. http://golang.org visited on May 18th 2012. [5] Google Developers. The Go Programming Language Promo. May 2012. http://www.youtube.com/watch?v=wwoWei-GAPo visited on May 18th 2012. [6] Miscellaneous. Wikipedia arcticle about Ken Thompson. May 2012. http: //en.wikipedia.org/wiki/Ken_Thompson visited on May 18th 2012. [7] Miscellaneous. Wikipedia arcticle about Rob Pike. May 2012. http: //en.wikipedia.org/wiki/Rob_Pike visited on May 18th 2012. [8] Frank Müller. Systemprogrammierung in Google Go - GrundlagenSkalierbarkeit- Performanz- Sicherheit. Dpunkt.Verlag GmbH, Heidelberg, 2011. Available in the university library.

I

List of Abbreviations amd64 is an extension of the i386 instruction set, it supports larger address spaces than i386 ARM ARM architecture is the most widely used 32-bit instruction set architecture in numbers produced, it is mostly used in tablets, mobile phones, music players, and calculators cbr call-by-reference, a called function is allowed to change variables in the main program cbv call-by-value, a called function recieves a copy of variables and can not change them in the main program i386 is an architecture that defines the instruction set for microprocessors, most personal computers use this set, it is currently replaced by amd64 Go Google Go GUI graphical user interface object-oriented programming is a programming technique using "objects" to interact within a data structures consisting of data fields and methods open source project everyone can support the developers and contribute to the base code and its future Plan 9 operating system from Bell Labs developed primarily for research purposes as the successor to Unix shell is software that provides an interface for users which provides access to the services of the main part of the operating system struct structure / record II

III TIOBE well-known programming language ranking on http://tiobe.com TIOBE award entitles the programming language of the year based on the ranking on TIOBE Unix operating system originally developed in 1969 and predecessor of many systems, e.g. Mac OS or Linux

Source Files List of Source Code 1: Hello world program implemented in Google Go 1 package main import " fmt " 4 func main () { fmt . Println ( " Hello world " ) 7 }

IV

V List of Source Code 2: Fibonacci Number calculation implemented in Google Go package main 2 // package import import ( . " fmt " 5 err " errors " ) 8 // function with 3 return values func fib (a , b int64 , n int ) ( int64 , int64 , error ) { // if - else chain - exception handling 11 switch { case n = 100: return 0 , 1 , err . New ( " Number higher / equal 100 , try again . " ) } 17 // calculation for i := int ( b ) ; i < n ; i ++ { b , a = a +b , b 20 } return a , b , nil } 23 // main procedure func main () { 26 var n int f . Printf ( " This program calculates the fibonacci numbers iterative .\ n " ) // while loop 29 for { f . Printf ( " Which fibonacci number should be computed ?\ n " ) f . Scanf ( " % d " , & n ) 32 // function call _ , res , err := fib (0 ,1 , n ) if err != nil { 35 f . Println ( err ) // error output } else { f . Printf ( " The fibonacci number of % v is % v \ n " ,n , res ) // result output 38 } } } 41 // 707 characters without comments

VI

SOURCE FILES List of Source Code 3: Fibonacci Number calculation implemented in Pascal

1 PROGRAM fibonacci ; USES crt ; // package import VAR n : INTEGER ; 4 res : LONGINT ; // function 7 FUNCTION Fibonacci ( n : INTEGER ) : LONGINT ; VAR i : INTEGER ; a ,b , c : LONGINT ; 10 BEGIN // calculation a := 0; b := 1; 13 FOR i := 2 TO n DO BEGIN c := a + b ; 16 a := b ; b := c ; END ; 19 Fibonacci := b ; END ; 22 // main procedure BEGIN Writeln ( ’ This program calculates the fibonacci numbers iterative . ’) ; 25 // while loop WHILE ( true ) DO BEGIN 28 REPEAT Writeln ( ’ Which fibonacci number should be computed ? ’) ; Readln ( n ) ; 31 // exception handling IF ( n = 100) THEN Writeln ( ’ Number higher / equal 100 , try again . ’) ; UNTIL ( n > 0) AND ( n < 100) ; 37 Writeln ; // function call res := Fibonacci ( n ) ; 40 Writeln ( ’ The fibonacci number of ’ , n , ’ is ’ , res ) ; // result output Writeln ; END ; 43 END . // 760 characters without comments

VII List of Source Code 4: Fibonacci Number calculation implemented in Java 1 public class Fibonacci { // function public static long fib ( int n ) 4 throws FibonacciNegativeException , FibonacciTooBigException { // if - else chain - exception handling if ( n = 100) throw new F i b o n a c c iT o o B i g E x c e p t i o n () ; 10 // calculation long a = 0 , b = 1 , c ; for ( int i = 2; i