CSC/ECE 517 Fall 2014/ch1a 10 hu

From Expertiza_Wiki
Jump to navigation Jump to search

Go Programming Language

Go, also commonly referred to as golang, is a compiled, concurrent, garbage-collected, statically typed language developed at Google. It was developed by Robert Griesemer, Rob Pike and Ken Thompson in 2007. It was announced in November 2009 and is currently being used in many production systems at Google. It is an open source project. The syntax is loosely derived from that of C programming language, adding Garbage collection, type safety, some dynamic-typing capabilities. Additional built-in types such as variable-length arrays and key-value maps, and a large standard library are also supported. Different operating systems like Linux, Microsoft Windows, Mac OS X are suported by Gc compiler of Go.

Background

Go programming started of as a research project by Robert Griesemer, Rob Pike and Ken Thompson. They felt that there was no new system focused programming language that has come up in the last decade till 2008, while there were other developments like increase in the size of libraries, dominance of networking , client server focus, multi-core CPUs.<ref name = "Background 1">Go Language Introduction speech</ref> So they wanted to come up with a new systems focused programming language that would address the above issues.<ref name="BG2">TechCrunch</ref> They started sketching the goals for a new language on the white board on September 21, 2007. Within a few days the goals had settled into a plan to do something and a fair idea of what it would be. Design continued part-time in parallel with unrelated work. By January 2008, Ken had started work on a compiler with which to explore ideas; it generated C code as its output. By mid-year the language had become a full-time project and had settled enough to attempt a production compiler. In May 2008, Ian Taylor independently started on a GCC front end for Go using the draft specification. Russ Cox joined in late 2008 and helped move the language and libraries from prototype to reality. Go became a public open source project on November 10, 2009. Many people from the community have contributed ideas, discussions, and code.<ref name = "Google_FAQ">golang FAQs</ref>

Compilers and Runtime support

There are two Go compiler implementations, Gc (the 6g program and friends) and gccgo . Gc uses a different calling convention and linker. It can therefore only be linked with C programs using the same convention. Gccgo is a GCC front-end that can be linked with GCC-compiled C or C++ programs.<ref name = "Google_FAQ"/>

The cgo program provides the mechanism for a “foreign function interface” to allow safe calling of C libraries from Go code. SWIG extends this capability to C++ libraries.

Again due to bootstrapping issues, the run-time code is mostly in C (with a tiny bit of assembler) although Go is capable of implementing most of it now. Gccgo's run-time support uses glibc. Gc uses a custom library to keep the footprint under control; it is compiled with a version of the Plan 9 C compiler that supports resizable stacks for goroutines. The gccgo compiler implements these on Linux only, using a technique called segmented stacks, supported by recent modifications to the gold linker.<ref name = "Google_FAQ"/>

You can find all resources needed to compile and run Go Language here http://go-lang.cat-v.org/

Design Principles

Programming today involves too much bookkeeping, repetition, and clerical work. As Dick Gabriel says, “Old programs read like quiet conversations between a well-spoken research worker and a well-studied mechanical colleague, not as a debate with a compiler. Who'd have guessed sophistication bought such noise?” The sophistication is worthwhile—no one wants to go back to the old languages—but can it be more quietly achieved?<ref name = "Google_FAQ">golang FAQs</ref>

Go attempts to reduce the amount of typing in both senses of the word. Throughout its design,

  • They have tried to reduce clutter and complexity.
  • There are no forward declarations and no header files. everything is declared exactly once.
  • Initialization is expressive, automatic, and easy to use.
  • Syntax is clean and light on keywords. Stuttering (foo.Foo* myFoo = new(foo.Foo)) is reduced by simple type derivation using the := declare-and-initialize construct.
  • And perhaps most radically, there is no type hierarchy. They don't have to announce their relationships.<ref name = "Google_FAQ">golang FAQs</ref>

These simplifications allow Go to be expressive yet comprehensible without sacrificing, well, sophistication. Another important principle is to keep the concepts orthogonal. Methods can be implemented for any type; structures represent data while interfaces represent abstraction; and so on. Orthogonality makes it easier to understand what happens when things combine.<ref name = "Google_FAQ">golang FAQs</ref>

Comparison between Go Programming and C++ Programming language

Points of Comparison Go Programming Language C++ Programming Language

Primary Focus

Go focuses on garbage collection, concurrency and compiling quickly Java is strictly an Object oriented programming language.

Variable Sizes

Machine-independent types are now included without an import needed: int8, int16, int32, int64, uint8, etc. Machine-dependent variable sizes

Class Hierarchies

Inheritance is not supported , but with the traditional structures with plain old functions and namespaces, is a MUCH

better, more flexible approach that leads to better, more maintainable code.

Inheritance is supported but it has its own share of problems like diamond inheritance, virtual inheritance and normal inheritance.

Interfaces

Interfaces are present in Go programming though it does not have the other features of Object Oriented languages. They have to be defined as abstract classes.

Function overloading

Not present in Go because it simplifies dispatch. Present in C++.

Genrics

Go does not currently support generic types. However, it does support objects without a type using the empty interface. C++ on the other hand has support for generic types. Generic programming is supported by the use of function templates, class templates and, in some cases, specialized templates in C++.

Multithreading

Goroutines are Go's model of threads/coroutines. Each new goroutine runs in parallel with the current computation, in "the same address space. Goroutines are cheap and developers need not to

worry about the stack size.

In contrast, there is currently no built-in way to manage threads in C++, although the feature is expected in the upcoming new standard and is already today possible using third-party libraries.

Garbage Collection

Go uses garbage collection for memory management, which means that if frees the programmer completely from keeping a track on the memory used. C++ does not have any garbage collection and hence relies heavily on that the programmer knows what he or she is doing.

Language Design<ref name = "GoLang Book">GoLang Book</ref>

Syntax

 package main //line 1

   import “fmt”  //line 2

   func main() {  //line 3

       fmt.Println(“Hello World”) //line 4

   } //line 5

Line1 specifies package declaration. Package is used to organize and reuse code. Line 2 is used for including the package “fmt” which is used for formatting input and output. Line 3 to 5 defines the function main. main is the function which is called when a program is executed. Println function in fmt is used to display content to the console i.e in this example Hello World is displayed in the console on executing the program.

Code Conventions and Style

  • Go fmt tool is used to automatically standardize indentation, spaces and surface-level code details. go vet and go link are perform checking automatically.
  • Using tools and libraries provided in Go, there are standard approaches for API documentation(go doc), testing(go test), building(go build) and package management(go get).
  • Syntax prevents any kind of cyclic dependencies.
  • Unused variables and imports are not allowed.
  • Elimination of functional programming constructs (such as map and try/finally in C++) ensure a concrete and explicit programming style.

Types

  • Numbers are represented in Go as either Integers or Floating point numbers.
    • Integers: Used to represent numbers without a decimal component. Different integers supported by Go are: uint8, uint16, uint32, uint64, int8, int16, int32, int64. Uint is used for unsigned integers and int for signed. 8,16, 32, 64 indicate the number of bits each type would use.
    • Floating Point Integers: Used to support decimal components. Go supports float32 and float64 to represent floating point numbers and complex32 and complex64 to represent complex numbers.

Example:

var x int32 =4
var y float32 = 4.5
  • String: String litersals can be created using either double quotes(“Hello”) or back ticks(`Hello`). Strings have several operations associated them, for example one can find the length of the string or get a character at a specific index in a string.

Example:

package main

import “fmt”

func main() {

	fmt.Println(len(“Hello”)) // output: 5
	fmt.Println(“Hello”[1]) // output: 1
	fmt.Println(“Hello “+”Tom”) //output: Hello Tom

}

  • Boolean: A 1 bit value is used to represent true or false.

Variables and Constants

  • Variabes in Go are indicated using the var keyword. Example: var x string=”hello” . They can also be shorthanded as x:=”hello” .
  • The variable names should begin with a letter and can contain letters, digits or underscore character.
  • The scope of the variable is the block in which it is defined and an attempt to access it outside the block would result in an error on running the program.
  • Go provides support for constants (i.e. variables whose value can not be changed), using the const keyword. Example: const temp string = “Hello”
  • In Go one can define multiple variables(or constants) using the following syntax:
   var(
        t1 =1
        t2=2
        t3=3
       t4=4

)

Control Structures

  • For: It is used for repeating a list of statement(s) multiple times. The example below is used for calculating sum of numbers from 1 to 10.

package main

import “fmt”

func main() {
    
    i := 1
    sum := 0

    for i <= 10 {
        sum = sum + i
        i = i + 1
    }
    
    fmt.Println(“Sum:” + sum)
}

In the example above i is a loop counter variable and is used to ensure that sum of numbers from 1 to 10 is computed. It indicates the number of times the statements inside the for loop is to be executed. The statement following the keyword for should evaluate to either true or false. If it is evaluated to true the body of for is executed, else we come out of the for loop.

  • If: Used to execute a block of statement(s) based on the evaluation of an expression to either true or false. It can also have an else associated with it.

Example:


package main

import “fmt”

func main(){

    if i % 2 == 0 {
        fmt.Println(i + ” is divisble by 2”)
    } else {
        fmt.Println(i + “is not divisible by 2”)
    }

}

  • Switch: The value of the expression following switch is evaluated and is compared against the different cases. Based on the matching case, the block following that case is executed. Switch also has a default case in situations when none of the cases are matching.

Example:


package main

import “fmt”

func main(){

    // if op ==1 then so a+b
    // if op == 2 then do a-b
    // if op == 3 then do a*b
    // if op ==4 then do a/b
    // default print, invalid operator

    op:= 1
    a=6
    b=7
    switch(op) {
        case 1: fmt.Println(a+b)
        case 2: fmt.Println(a-b)
        case 3: fmt.Println(a*b)
        case 4: fmt.Println(a/b)
        default: fmt.Println(“Invalid Operator”)
    }

}

Arrays, Slices and Maps

  • Arrays: Numbered sequence of elements starting with index zero and each of the elements having a fixed length. The example below illustrates various operations performed on arrays in Go.

package main

import “fmt”

func main() {

    var x[10] int
    x[99]=100
    fmt.Println(x)  //[0 0 ….. 0 100]
    fmt.Println(len(x)) //100

}

  • Slices:
    • It is a segment of an array.
    • They have a length and are indexable.
    • In case of a slice the size does not have to specified in the square bracket.
    • Slices support two in-build functions: copy and append.
    • The program below illustrates the different ways to create slices and use of copy and append.

package main

import “fmt”

func main() {
    
    arr := [10] int {1,2,3,4,5,6,7,8,9,10}
    x := make([]int,10) // creates a slice [1...10]
    y := make([]int,10,10) //creates a slice [1...10]
    z := arr[0:10] //creates a slice [1...10]
    s1 := []int{1,2,3,4,5}
    s2 := append(s1, 6, 7)
    fmt.Println(s1) // [1,2,3,4,5]
    fmt.Println(s2) // [1,2,3,4,5,6,7]
    p1 := [] int{1,2,3,4,5}
    p2 :=make([]int, 4)
    copy(p2,p1)
    fmt.Println(p1) // [1,2,3,4,5]
    fmt.Println(p2)// [1,2,3,4]
}


  • Maps:
    • A map is an unordered collection of key value pairs.
    • Syntax: var x map[int] string , where int is the type of the key and string is the type of the value.

Example


package main

import “fmt”

func main(){
    
    x := make(map[int]string)
    x[1] = one
    x[2] = two

}

Functions

  • In Go functions can take multiple inputs and return multiple outputs.
  • Go supports a special kind of function called variadic function.
  • Closure is the means by which functions can be created inside other function in Go.
  • Go supports recursive functions.
  • The example below the different types of function in Go.
package main

import “fmt”

func main(){

    display(“Hello World”)
    sum :=calculateSum(10,20)
    v1,v2=multipleValues()
    p=product(5,10,20)
}

// function without return type
func display( s string) {
    fmt.Println(s)
}

// function which returns a single value
func calculateSum(a int, b int) int {
    c: = a + b
    return c
}

// function which returns multiple values
func multipleValues(int, int) {
    return 1, 2
}

//Variadic function
func product(args ...int) int {
    p := 1
   for _, i := range args {
        p *= i
   }
   return p
}

Pointers

It is used to reference a location in the memory where the value is stored rather than containing the value itself. Basic pointer operations in Go are illustrated in the example below.


package main

import “fmt”

func main(){
    
//Different syntax for pointers
    
     ptr1 *int
     num :=10
     ptr1 = &num
     ptr2 := new(int)
     ptr2=&num

}

Concurrency

  • Go ensures concurrency which allows sharing of state using communication mechanisms.
  • Go provides support for multithreading and CPU parallelization.
  • Go supports asynchrony i.e. allows operations like database and network I/O which are slow operations to occur in parallel along with other operations.
  • A new lightweight process is created using go fund()
  • Channel types are used for providing type safe and synchronized channels between different go routines.

Users of Go

Apart from Google, which uses Go programming for some of its development, companies like Dropbox, CloudFlare, SoundCloud, The BBC, Novartis, Cloud Foundry also use Go programming. Dropbox server (running in the cloud) and desktop client software were primarily written in Python. From mid-2013 Dropbox began migrating its backend infrastructure to Go. Some of the open-source applications that are using Go programming are Docker, Flynn, PaaS, Juju, nsq, Doozer e.t.c .<ref name = "GoWIKI">Wikipedia</ref>

Advantages<ref name="csdn"> CSDN blog</ref>

  • C Level Performance. golang is within a close margin of the performance level of C code (which is itself an extremely high performance language). It is certainly closer to the performance of native languages than other enterprise level languages such as Java, Scala, Erlang etc.
  • Fast Compilation is one of the key advantages of Go language. The Golang compiler was designed to compile programs very quickly. Extremely large programs with massively high LOC counts compile seemingly instantly - after all, Golang was designed by Google to solve Google problems, and Google has big problems! At Google, code and CPU cores are both measured in the millions. Go provides a model for software construction that makes dependency analysis easy and avoids much of the overhead of C-style include files and libraries.<ref name = "Limitations1"/>

Reduced compile time is a key improvement in the Go language

      If A.go depends on B.go depends on C.go :
         Compile C.go, B.go then A.go normally (other languages)
         To compile A.go, compiler reads B.o not C.o (go)

At a large scale this should help in hugely speeding up

Other advantages are

  • Concurrency Supported At Language Level. Concurrency is the ability to execute multiple computations simultaneously. In today's modern multicore and high-load computing environment, concurrency is a critical language feature, and one in which languages such as Java struggle immensely.
  • By its design, Go proposes an approach for the construction of system software on multicore machines.<ref name = "Google_FAQ"/>
  • Google have summed things up nicely with their motto: Don't communicate by sharing memory, share memory by communicating.Channels allow you to pass references to data structures between goroutines. If you consider this as passing around ownership of the data (the ability to read and write it), they become a powerful and expressive synchronization mechanism.
  • Go's type system has no hierarchy, so no time is spent defining the relationships between types. Also, although Go has static types, the language attempts to make types feel lighter weight than in typical Object Oriented languages.
  • Garbage Collection is much better. In C and C++, programmers spend a lot of time and energy on allocating and freeing memory. The designers of Go wanted to remove that complication, and ensure Go programmers could concentrate on more productive tasks. As such, they implemented garbage collection. As a developer, this is a very good thing. Sure, garbage collection comes with its own set of issues, but those are dealt with by the language implementer while the programmer is free to reap the other many benefits of Go.

Limitations

  • Go is still an experimental language subject to change.<ref name = "Limitations1">stackoverflow</ref>
  • Go's not very usable on Windows yet.
  • The packages distributed with Go are pretty useful, but there are still some libraries you'll miss. Most notably a UI toolkit.
  • There is no support for generics in Go, although there are many discussions around it.
  • Confusing Semantics Of Exported Identifiers<ref name = "Limitations2">

functionwhatwhat </ref>

References

<references />