Go Introduction

by "Blag" - Senior Developer Evangelist

What is Go?


Go is a compiled, concurrent, imperative and structured programming language.


Developed at Google...it's Open Source.


Created by Robert Griesemer (Java HotSpot Virtual Machine), Rob Pike (Plan 9 and Inferno OS, Limbo programming language, and Ken Thompson (C, Unix, Plan 9, UTF-8).


It's basically C without the makeup...

How to install Go?


For Linux and MacOS it can downloaded from here Go


tar -C /usr/local -xzf go$VERSION.$OS-$ARCH.tar.gz


export PATH=$PATH:/usr/local/go/bin


For Windows it can be installed from an MSI installer from here Go

Who uses Go?


  • Google -> They created...so...
  • Paypal
  • Twitter
  • Dropbox.
  • MongoDB.
  • Heroku.
  • Khan Academy.
  • SoundCloud.

Starting out...


Go doesn't come with an IDE, so we can use Geany


To configure Geany for Go, please follow this link Running Go on Geany


Otherwise, you can use any other editor and simply do...

go build "filename.go" //To compile and generate and executable

go run "filename.go" //To just run the code

Basic Concepts


One line comments are // and multiple lines comments are /* and */.

Each program start with a package

				
package main
				

And a main function

				
func main()
				

And imports at least one library

				
import "fmt"
				

Basic Concepts


Printing on the screen is easy...


				
fmt.Print("This is Go!")

This is Go!


fmt.Println("This is Go!)

This is Go!

				

Variables

				
var sText string

sText = "This is a string"

sText := "This is a string"
				

Go is statically typed, but it can use inference...

Arrays

				
var aNumber[5]int


aNumber[0] = 1

aNumber[1] = 2

aNumber[2] = 3

aNumber[3] = 4

aNumber[4] = 5


fmt.Print(aNumber)

[1 2 3 4 5]				
				
				
aNumber := [5]int{1, 2, 3, 4, 5}


fmt.Print(aNumber)

[1 2 3 4 5]
				

Just two ways of doing exactly the same thing...

Slices

Slices are just like arrays...but it's length can change...

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


fmt.Println(slice)

[1 2 3]


other_slice := append(slice, 4, 5)


fmt.Println(other_slice)

[1 2 3 4 5]


more_slice := make([]int, 2)

copy(more_slice, other_slice)

fmt.Print(more_slice)

[1 2]
				

Maps

Maps are the same as associate arrays, hash tables or dictionaries

				
sMap := make(map[string]string)


sMap["One"] = "First"

sMap["Two"] = "Second"

sMap["Three"] = "Third"


fmt.Println(sMap)

map[Three:Third One:First Two:Second]
				
				
for key, value := range sMap {
	
    fmt.Println(key, value)
    
}



One First

Two Second

Three Third    
				

For

For is the only loop structure...

				
i := 1

for i <= 5 {
	
    fmt.Println(i)
    
    i++
    
}


1

2

3

4

5
				

We can also write in the old fashion way...


				
for i := 1; i <= 10; i++ {
	
    fmt.Println(i)
    
}


1

2

3

4

5   
				

Making an LED Number App


Finally...we're going to make our first application...


So grab your favorite text editor and get ready...


Name your file "LED_Numbers.go"


				
package main

import "fmt"

func main() {

	fmt.Print("Enter a number: ")

	var num string

	fmt.Scanf("%s", &num)

	leds := map[string][]string {

		"0" : []string{" _  ","| | ","|_| "},

		"1" : []string{"  ","| ","| "},

		"2" : []string{" _  "," _| ","|_  "},

		"3" : []string{"_  ","_| ","_| "},

		"4" : []string{"    ","|_| ","  | "},

		"5" : []string{" _  ","|_  "," _| "},
				
				
		"6" : []string{" _  ","|_  ","|_| "},

		"7" : []string{"_   "," |  "," |  "},

		"8" : []string{" _  ","|_| ","|_| "},

		"9" : []string{" _  ","|_| "," _| "},

	}


	for i := 0; i < 3; i++ {

		for j := 0; j < len(num); j++ {

		   fmt.Print(leds[string(num[j])][i])

		}

		fmt.Print("\n")

	}

}
				

Open the Terminal and go to your source code folder...

go run "Name_of_File.go"


When we run it we're going to see...


Random Names


This App will generate 100,000 random names using two 16 elements arrays


We will measure the runtime


Name your file "Random_Names.go"


				
package main

import ( "fmt";"math/rand";"time" )


func main() {

    start := time.Now()
    
    names := [16]string{"Anne","Gigi","Blag","Juergen",
		
                        "Marek","Ingo","Lars","Julia",
                        
                        "Danielle","Rocky","Julien",
                        
                        "Uwe","Myles","Mike",
                        
                        "Steven","Fanny"}
				
				
    last_names := [16]string{"Hardy","Read","Tejada",
		
                             "Schmerder","Kowalkiewicz",
                             
                             "Saurzapf","Karg",
                             
                             "Satsuta", "Keene",
                             
                             "Ongkowidjojo","Vayssiere",
                             
                             "Kaylu","Fenlon","Flynn",
                             
                             "Taylor","Tan"}
                             
        
                           
    full_names := make([]string, 100000)
    
    i := 1
    
    for i < 100000 {
		
        full_names[i] = names[rand.Intn(15)] + 
        
                        last_names[rand.Intn(15)]
        
        i++ }           
			
				
    elapsed := time.Since(start)
    
    fmt.Println("Time: ", elapsed.Seconds())
    
    fmt.Println(len(full_names), " names generated")
    
}  
			

When we run it we're going to see...

How this behaves in Julia?

How this behaves in Python?

Go won the race...by little...

Decimal to Romans


This App will create a Roman Numeral based on a decimal number


This will include some nice commands...


Name your file "DecToRoman.go"


				
package main

import ( "fmt" )


func main() {

	fmt.Print("Enter a number: ")

	var num int

	fmt.Scanf("%d", &num)

	Romans := map[int]string {

		1000:"M", 900:"CM", 500:"D", 400:"CD",

		100:"C", 90:"XC", 50:"L", 40:"XL", 
		
		10:"X", 9:"IX", 5:"V", 4:"IV", 1:"I",

	}

	fmt.Println(Roman_Number(num, Romans))

}
			
				
func Roman_Number(num int, counter int, 

                  Romans map[int]string) string{

	Keys := [13]int{1000,900,500,400,100,90,50,40,
		
		        10,9,5,4,1}

	result := ""

	for {

		if num >= Keys[counter] {

		    result += Romans[Keys[counter]]

		    num -= Keys[counter]

		} else { counter++ }

		if num <= 0 { break }

	}

	return result

}   
			

When we run it we're going to see...


Couting Letters


In this example we're going to read a file and count how many time a letter appears...


Call your file "countletters.go" (all in lowercase).


Create a file called "readme.txt" with the following text...


"This is a text file that we're going to read it using Go"

				
package main

import ( "fmt"; "io/ioutil"; "strings" )


func main() {

    file, err := ioutil.ReadFile("readme.txt")

    if err != nil {

        fmt.Print("Couldn't open the file")

        return

    }
				
				
    str := string(file)

    str = strings.Replace(str, "\n", "", 1)

    Chars := strings.Split(str, "")

    charmap := make(map[string]int)

    for _, value := range Chars {

        charmap[value] += 1

    }

    for key, value := range charmap {

        fmt.Print("(", key, ", ")

        fmt.Println("\"", value, "\")")

    }

}
				

When we run it we're going to see...


Serving Web Pages


Like almost every language...Go can handle web pages too...


Without needing any external packages...


It also supports HTML templates...


Create a file called "message.gtpl" and another one called "webserver.go

				
<html>

<head>

<title></title>

</head>

<body>

<form action="/login" method="post">

    Name:<input type="text" name="name">

    <input type="submit" value="Greet me!">

</form>

</body>

</html>
				
				
package main

import ( "io";"fmt";"html/template";"log";"net/http" )


func login(w http.ResponseWriter, r *http.Request) {

    fmt.Println("method:", r.Method)

    if r.Method == "GET" {

        t, _ := template.ParseFiles("message.gtpl")

        t.Execute(w, nil)

    } else {

        r.ParseForm()

        message := "Hello from Go, dear " + 
                   
                   r.Form["name"][0] + "!"

        io.WriteString(w, message)

    }

}
				
				
func main() {

    http.HandleFunc("/", login)

    err := http.ListenAndServe(":8080", nil)

    if err != nil {

        log.Fatal("ListenAndServe: ", err)

    }

}
				

When we run it we're going to see...


Of course...that just plain simple...let's try something more interesting...


Name your file "fibo.gtpl" and the other "webserver_Fibonacci.go"


				
<html>

<head>

<title></title>

</head>

<body>

<form action="/get_fibo" method="post">

    Enter a number: <input type="text" name="number">

    <input type="submit" value="submit">

</form>

</body>

</html>
				
				
package main


import ( "io";"fmt";"html/template";"log";

         "net/http";"strconv" )


func fibo(number int) string{

	result := "0"

	fib := 1

	first := 0

	second := 1

	i := 0
				
				
	for i < number {

		result = result + " " + 
		
		         strconv.Itoa(fib)

		fib = first + second

		first = second

		second = fib

		i++

	}

	return result

}
				
				
func get_fibo(w http.ResponseWriter, r *http.Request) {

    fmt.Println("method:", r.Method)

    if r.Method == "GET" {

        t, _ := template.ParseFiles("fibo.gtpl")

        t.Execute(w, nil)

    } else {

        r.ParseForm()

        number := r.Form["number"][0]

        num,_ := strconv.Atoi(number)

        result := "The Fibonacci sequence is: " 
		
                  + fibo(num)

        io.WriteString(w, result)

    }

}
				
				
func main() {

    http.HandleFunc("/", get_fibo)

    err := http.ListenAndServe(":8080", nil)

    if err != nil {

        log.Fatal("ListenAndServe: ", err)

    }

}
				

When we run it we're going to see...


That's all...


Go is still kind of a new language

More interesting thing will appear in the future...

Contact Information


Blag --> blag@blagarts.com

@Blag on Twitter

Go back home...