introduction to go language programming

54
Introduction to go language programming Mahmoud masih tehrani Clickyab Spring 2016

Upload: mahmoud-masih-tehrani

Post on 19-Feb-2017

272 views

Category:

Education


5 download

TRANSCRIPT

Introduction to go languageprogramming

Mahmoud masih tehraniClickyab

Spring 2016

Golang history

Robert Griesemer, Rob Pike and Ken Thompson 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.

Go is multiplatformGoogle's Go compiler, "gc", is developed as open source software and targets various platforms including Linux, OS X, Windows, various BSD and Unix versions, and since 2015 also mobile devices, including smartphones. A second compiler, gccgo, is a GCC frontend.The "gc" toolchain is self-hosting since version 1.5

Why go?Go is easier to write (correctly) than C.

Go is easier to debug than C (even absent a debugger).

Go is the only language you'd need to know; encourages contributions.

Go has better modularity, tooling, testing, profiling, ...

Go makes parallel execution trivial.

Benchmark with go,ruby,python,node,php

https://www.techempower.com/benchmarks

How install go and use that!?Install : sudo apt-get install golang

Show version : go version

>>go version go1.6.1 linux/amd64

Show help : go help

Run code : go run YOUR_PACKAGE_NAME.go

Compile code : go install YOUR_PACKAGE_NAME.go

Which IDE for go● Sublime Text 2

● IntelliJ

● LiteIDE

● Netbeans

● Eclipse

● TextMate

● Komodo

● vim

● Emacs

Getting start to learn gopackage main

import ("fmt")

func main() {

fmt.Println("Hello, محمود")

}

Comment// comments in which all the

text between the // and the end of the line is part of

the comment and /* */ comments where everything

between the * s is part of the comment. (And may in-

clude multiple lines)

Install packages

1. Download and install it:

$ go get github.com/gin-gonic/gin

2. Import it in your code:

import "github.com/gin-gonic/gin"

Types in goInteger:

uint8 , uint16 , uint32 , uint64 ,

int8 , int16 , int32 and int64

Floating point:

float32 and float64

String:

string

operators+ addition

- subtraction

* multiplication

/ division

% remainder

stringsString literals can be created using double quotes

"Hello World" or back ticks `Hello World` . The differ-

ence between these is that double quoted strings can-

not contain newlines and they allow special escape se-

quences. For example \n gets replaced with a newline

and \t gets replaced with a tab character.

stringspackage main

import "fmt"

func main() {

fmt.Println(len("Hello World"))

fmt.Println("Hello World"[1])

fmt.Println("Hello " + "World")

}

Booleans&& and

|| or

! not

Booleansfunc main() {

fmt.Println(true && true)

fmt.Println(true && false)

fmt.Println(true || true)

fmt.Println(true || false)

fmt.Println(!true)

}

Booleans$ go run main.go

true

false

true

true

false

variablespackage main

import "fmt"

func main() {

var x string = "Hello World"

fmt.Println(x)

}

variablespackage main

import "fmt"

func main() {

var x string

x = "Hello World"

fmt.Println(x)

}

variablespackage main

import "fmt"

func main() {

var x string

x = "first"

fmt.Println(x)

x = "second"

fmt.Println(x)}

variablesvar x string

x = "first "

fmt.Println(x)

x = x + "second"

fmt.Println(x)

variablesvar x string = "hello"

var y string = "world"

fmt.Println(x == y)

>>false

variablesX := "Hello World"

Naming variablesname := "Max"

fmt.Println("My dog's name is", name)

dogsName := "Max"

fmt.Println("My dog's name is", dogsName)

scopepackage main

import "fmt"

func main() {

var x string = "Hello World"

fmt.Println(x)

}

scopevar x string = "Hello World"

func main() {

fmt.Println(x)

}

func f() {

fmt.Println(x)

}

scopefunc main() {

var x string = "Hello World"

fmt.Println(x)

}

func f() {

fmt.Println(x)

}

Constantspackage main

import "fmt"

func main() {

const x string = "Hello World"

fmt.Println(x)

}

Constantsconst x string = "Hello World"

x = "Some other string"

>>.\main.go:7: cannot assign to x

Defining Multiple Variablesvar (

a = 5

b = 10

c = 15

)

An Example Programpackage main

import "fmt"

func main() {

fmt.Print("Enter a number: ")

var input float64

fmt.Scanf("%f", &input)

output := input * 2

fmt.Println(output)

}

Forpackage main

import "fmt"

func main() {

i := 1

for i <= 10 {

fmt.Println(i)

i = i + 1

}

}

Forfunc main() {

for i := 1; i <= 10; i++ {

fmt.Println(i)

}

}

If1 odd

2 even

3 odd

4 even

5 odd

6 even

7 odd

8 even

9 odd

10 even

Iffunc main() {

for i := 1; i <= 10; i++ {

if i % 2 == 0 {

fmt.Println(i, "even")

} else {

fmt.Println(i, "odd")

}

}

}

switchswitch i {

case 0: fmt.Println("Zero")

case 1: fmt.Println("One")

case 2: fmt.Println("Two")

case 3: fmt.Println("Three")

default: fmt.Println("Unknown Number")

}

Arraypackage main

import "fmt"

func main() {

var x [5]int

x[4] = 100

fmt.Println(x)

}

>>[0 0 0 0 100]

Arrayvar total float64 = 0

for i := 0; i < len(x); i++ {

total += x[i]

}

fmt.Println(total / len(x))

>># command-line-arguments

.\tmp.go:19: invalid operation: total / 5 (mismatched types float64 and int)

Arrayfmt.Println(total / float64(len(x)))

Arrayx := [5]float64{ 98, 93, 77, 82, 83 }

Slicefunc main() {

slice1 := []int{1,2,3}

slice2 := append(slice1, 4, 5)

fmt.Println(slice1, slice2)

}

mapsvar x map[string]int

x["key"] = 10

fmt.Println(x)

elements := map[string]string{

"H": "Hydrogen",

"He": "Helium",

"Li": "Lithium",

"Be": "Beryllium",

"B": "Boron",

"C": "Carbon",

}

mapselements := map[string]map[string]string{

"H": map[string]string{

"name":"Hydrogen",

"state":"gas",

},

"He": map[string]string{

"name":"Helium",

"state":"gas",

},}

mapsif el, ok := elements["He"]; ok {

fmt.Println(el["name"], el["state"])

}

functionfunc average(xs []float64) float64 {

total := 0.0

for _, v := range xs {

total += v

}

return total / float64(len(xs))

}

functionfunc main() {

xs := []float64{98,93,77,82,83}

fmt.Println(average(xs))

}

functionfunc f() (int, int) {

return 5, 6

}

func main() {

x, y := f()

}

func add(args ...int) int {

total := 0

for _, v := range args {

total += v

}

return total}

func main() {

fmt.Println(add(1,2,3))

}

Closurefunc main() {

add := func(x, y int) int {

return x + y

}

fmt.Println(add(1,1))

}

deferpackage main

import "fmt"

func first() {fmt.Println("1st")}

func second() {fmt.Println("2nd")}

func main() {defer second()

first()

}

deferf, _ := os.Open(filename)

defer f.Close()

panicpackage main

import "fmt"

func main() {

panic("PANIC")

str := recover()

fmt.Println(str)

}

referenceWikipedia.com

Golang.com

An Introduction to Programming in Go (go book) Caleb Doxsey