Before we start making program we must first install all the required packages which we need. In this section I'll be using Ubuntu GNOME 14.04 LTS OS and I'll tell you how to make program and how to run it.

List of topics I have covered :

1. Getting Started
2. Functions
3. Variables
4. For loop
5. If statement
6. Switch
7. Structs
8. Slices
9. Maps

Getting Started

Now at first we have to make sure that we have install go language in your system. If you haven't done it already then you can install it from here

sudo apt-get install golang

After installing go language, now we can start making our first program. Now lets get started by making your first program. First lets open your editer which you use (Vim,sublime etc) and create file with name hello.go . Whenever we make any go language program we use .go file extension and then save it like that. Now we'll edit and start making 'Hello World' program.

package main

import "fmt"

func main() {
    fmt.Println("Hello World")
}

After writing this code in hello.go file save that file and then open terminal. After opening terminal go to that directory where your file is and then type:

go run hello.go

This command will execute that file and then it will show the output in that terminal. Now it seems like we have successfully run our first program with go language but what else we can do. Well there are loads of things to learn. So lets get started by learning more about go programming language.

Fact: Go language is case sensitive if you write Println and println then it will give error so make sure not to do that

Functions

Declaring function in go language is not that hard and it can done easily. For making function we use:
func function_name(variable_name variable type) function_type{
    // Your task
} 
Here we must note that the brackets which is used in function is in same line. If we will use that bracket after new line then the compiler will print an error so we must avoid that mistake.
Now lets take example of real function returning a value.

func addition(a int, b int) int{
    return a+b
}

Here function can take zero or more argument so its upto you that how to use function. As in above function code it takes 2 arguments of int type and then return the value by adding it as an int type. To call the function we use:

fmt.Println(addition(1+2))

in main function inside brackets. It calls addition function and send 1 and 2 int variable and then when it adds up it return the final values and then Println print the value. Here Println means "Print line" so that it can easily be remember.

Fact: Package fmt implements formatted I/O with functions analogous to C's printf and scanf.

If there are 2 function variable of same type so to avoid typing int type twice we can avoid doing it by typing:

a, b int

Variables

To declare a list of variables we use var statement to declare it and type is in last. For example:

var x int

It will create a variable name x of integer datatype.
Now we can also declare variable initializer easily. For example:

var x = 2

Now this will create variable x with value 2. Now we must note that now variable x is of integer datatype because we have declared integer type to x. Let us take one experiment and understand what's happening and see the result:

var x = 2 // x is of integer type now

var x int = 2 // already integer type no error

var x int = "hey" // Error: cannot use "hey" (type string) as type int in assignment

Now it's pretty much clear now how this is working.

Fact: Inside function we can also use the := short assignment statement in place of var declaration but outside the function statement is always begin with either var or func etc. Example :

a := 5

Without any declaration by defualt integer type has 0 value, false for boolean type and "" for string type.

For loop

Its quite fascination but Go language has only one looping construct which is for loop. for loop is pretty much similar to C and Java but much better than that. Let's take a quick example to learn how to use it.

package main

import "fmt"

func main() {
    sum := 0
    for i := 0; i < 10; i++ {
        sum += i
    }
    fmt.Println(sum)
}
Here we must note that brackets () are not required and it is optional. Let us observe what is happening:

In for loop first i variable is assigned with value 0. So this loop says that i is equal to 0 and if i is less than 10 then increment the value of i by 1 and then put sum = sum + i. Now let us observe that will be value and how it will run :

0 = 0 + 0

0 = 0 + 1

1 = 1 + 2

3 = 3 + 3

6 = 6 + 4

10 = 10 + 5

15 = 15 + 6

21 = 21 + 7

28 = 28 + 8

36 = 36 + 9

45 = 45 + 10 // It will give error as 10 < 10 is false

Answer: 45

So now we come to know that how loop works in Go.

Fact: C's 'while' is spelled 'for' in Go. How ? Lets see example :

 sum := 1
    for sum < 100 {
        sum += sum
    }
    fmt.Println(sum)
    
Here you must notice that it is for loop only but in this case pre and post statements are empty so by that it can be used as while

If statement

If statement is also similar to C and java but again it is much better that here we don't have to use brackets (). Let us see how it is work :

     if x < 0 {
        fmt.Println("Hey")
    }
 
It is pretty much obvious that if x is less that 0 then it will print Hey.
Let's see how else will work. else is always placed where the if brackets are closed. See the sample code :
 if x < 0 {
        fmt.Println("Hey")
    } else {
        fmt.Println("Hi")
    }
    
Note here that if you will type else in new line then it will show error.

Switch

Switch is pretty much similar and its not that different. For example:
     switch c {
case '1':
    fmt.Println("It is 1")
case '2'':
    fmt.Println("It is 2")
case '3':
    fmt.Println("3 is awesome")
case '4':
    fmt.Println("4 is four")
case '5':
    fmt.Println("five is great")
default:
    fmt.Println("Sorry")
}
        
Here it will check the cases on variable c. If c will have '1' integer type then it will "It is 1" and such like that it will check all the cases. default case is run when all the cases above that doesn't statisfy.

Fact: Switch without a condition is same as switch true. So if we want to create any condition then simply make your condition after case like

case c < 100

where c is any variable with integer value.

Structs

Structs can be defined as a collection of data(fields). It is declated by typing 'type'. Here is the sample code to know how it works:


    type Vertex struct {
         x int
         y int
}
    
    

Now this will create struct with name Vertex having x,y as integer type.
Now these fields can be accessed by using dot. For example if we want to print the value of x from Vertex struct then :


    type Vertex struct {
        x int
        y int
    }
    func main() {
        v := Vertex{}
        v.X = 4
        fmt.Println(v.X)
    }
    

Now this will print the value 4. Here 'v.X = 4' is accessing the x variable in struct Vertex and assigning the value 4 to it.

Slices

Slice points to an array of values. It can be used by '[]A' which means this slice has elements of type A. Let us see one example:

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

Here []int is a slice with elements of type int which are 1,2,3,4,5,6. If we will try to print a then it will give:

[1 2 3 4 5 6]

Fact: Slices of slices is also possible and to implement it is also easy. Here is the sample code:


    a := [][]int{
        []int{1,2,3},
        []int{4,5,6},
        []int{7,8,9},
    }
    
Now if you will print a then you'll notice it it will look like: [[1 2 3] [4 5 6] [7 8 9]]. Here there is a slice of int which contain 3 other slices of int type which is containing different numbers.

Maps

A map maps keys to values. It is created by typing 'make' at starting. For example suppose we have struct 'my' then:

package main

import "fmt"

type my struct {
    int
}

var m map[string]my

func main() {
    m = make(map[string]my)
    m["world"] = my{
        3 - 1,
    }
    fmt.Println(m["world"])
}
    
Here variable m map string of my. And then assigning m["world"] to 3 - 1 having int type. By doing that m["world"] will be equal to 2 and then it will execute then it give output {2}.

So by now it was pretty much fun working with Go language and we got loads of information. At their official site you can see the Tour of Go language where you can learn even more.



Google+ Github Facebook Stackoverflow