A One Pager Tutorial of Go

Hello programmers, how are you guys. A friend asked me for a crash course on Golang. So, I am making it really short. This post will be helpful for programmers who are new to Go and don’t know where to go in Golang. I will write a basic tutorial with links, so be ready for a fast pace tutorial or a simple crash course.

I will cover the following topics:

  • What is Go (little-little)
  • How to install and configure.
  • Run first go program.
  • Go types and variables and scope
  • Arrays , Slices and Maps
  • If-else and switch
  • Loops
  • Functions and Closures
  • Structure and Interfaces

What is Go

I will say it’s another programming language. I learned it because, being C++ programmer I was in need of a language which is same as C or C++ in terms of performance and helps me to code my small services which runs on network and devlopment is really fast paced . So, I start reading about Go and fell in love with the language. If you need some boogie details of go history visit, gaolang.org, it says, “Go is an open source programming language that makes it easy to build simple, reliable, and efficient software.

How to install and configure

Go to Golang Website and just download it, on windows it is installed in C:\Go and On Mac it goes in /usr/local/go. As a beginer you just need to install and you are ready to run the program.

Note: I downloaded Intelij Idea and installed a plugin for Golang.

GOPATH 

The GOPATH environment variable specifies the location of your workspace. It is likely the only environment variable you’ll need to set when developing Go code.You can use GOPATH once you are able to run simple applications in Golang.

First GO Program

Create a file named, main.go

// go program need a package main
package main

// to use any golang functionality we need to import it.
import "fmt"

func main() {
 // Println is function of fmt package
 fmt.Println("Hello Friends")
}

Run it using, # go run main.go

=============================================
output:
Hello Friends

=============================================

Note: You can also run your programs online @Go Tour.

Go Types and Variables and Scope

Numbers

  • Integers ( uint8, uint16, uint32, uint64, int8, int16, int32 and int64 )
  • Float  : Go has two floating point types: float32 and float64 (also often referred to as single precision and double precision respectively)

Strings

  • “Rajni” , “Friends” are example of Golang string.

Booleans

  • true and false are two states of boolean

Variables

Variables in Golang are same as any other language. But their way of representation is different. They are declared as follows:

var variableName variableType

e.g. Lets write code.

package main

import "fmt"

func main() {
    // declare a variable and assign
    var myInt int = 10
    
    //auto type deduction using :=
    myInt2 := 20

    var myStr string = "Hello"

    myStr2:= "World"

    fmt.Println(myInt + myInt2)
    //string addition works in Golang
    fmt.Println(myStr + myStr2)
}

output:
30
Hello World

Variable Scope

package main 

import "fmt" 

//global variable scope 
var x string = "Hello World Global" 

func main() 
{ 
    fmt.Println(x) f() 
} 

func f() 
{ 
    // local variable scope 
    var x string = "Hello World Local" 
    fmt.Println(x) 
}


Arrays and Slices

var a [4]int //an array of integers size 4
b := [2]string{"Penn", "Teller"} // string array

Array are same as other programming language arrays, but the the way to declare them is a bit different. Lets do an example:

package main

import "fmt"


func main(){
       //array example
       var intarray [4]int
       intarray[0] = 1
       intarray[1] = 2
       intarray[2] = 3
       intarray[3] = 4
       fmt.Println(intarray)

       b := [2]string{"test1", "test2"}
       fmt.Println(b)
       b[0] = "new_test"
       fmt.Println(b)
}

Output:

[1 2 3 4]
[test1 test2]
[new_test test2]

Slices Example

package main

import "fmt"


func main(){
 //array example
 var intarray [4]int
 intarray[0] = 1
 intarray[1] = 2
 intarray[2] = 3
 intarray[3] = 4
 fmt.Println(intarray)

 //example of a slice, we sliced array from 1 to 3 
 b := intarray[1:3]
 fmt.Println(b)

}

Maps In Golang

They are also known as dictionaries, a sample code to use them, :

package main

import "fmt"


func main(){

       a := make(map[string]string)
       a["Myname"] = "Rajni"
       a["MyJob"] = "No Job"

       fmt.Println(a)
       fmt.Println(a["Myname"])
       fmt.Println(a["MyJob"])
       //check non existent
       fmt.Println(a["Noval"])

}

If-else

// Branching with `if` and `else` in Go is
// straight-forward.

package main

import "fmt"

func main() {

       // Here's a basic example.
       if 7%2 == 0 {
              fmt.Println("7 is even")
       } else {
              fmt.Println("7 is odd")
       }

       // You can have an `if` statement without an else.
       if 8%4 == 0 {
              fmt.Println("8 is divisible by 4")
       }

       // A statement can precede conditionals; any variables
       // declared in this statement are available in all
       // branches.
       if num := 9; num < 0 {
              fmt.Println(num, "is negative")
       } else if num < 10 {
              fmt.Println(num, "has 1 digit")
       } else {
              fmt.Println(num, "has multiple digits")
       }

       name := "rajni"

       if name == "rajni" {
              fmt.Println("Hi Rajni")
       } else {
              fmt.Println("Bye Rajni")
       }
}

output:
7 is odd
8 is divisible by 4
9 has 1 digit
Hi Rajni

 

Switch-Case

// _Switch statements_ express conditionals across many
// branches.

package main

import "fmt"
import "time"

func main() {

       // Here's a basic `switch`.
       i := 2
       fmt.Print("Write ", i, " as ")
       switch i {
       case 1:
              fmt.Println("one")
       case 2:
              fmt.Println("two")
       case 3:
              fmt.Println("three")
       }


       switch time.Now().Weekday() {
       
       case time.Saturday, time.Sunday:
              fmt.Println("It's the weekend")
       default:
              fmt.Println("It's a weekday")
       }

       // `switch` without an expression is an alternate way
       // to express if/else logic. Here we also show how the
       // `case` expressions can be non-constants.
       t := time.Now()
       switch {
       case t.Hour() < 12:
              fmt.Println("It's before noon")
       default:
              fmt.Println("It's after noon")
       }

       // A type `switch` compares types instead of values.  You
       // can use this to discover the the type of an interface
       // value.  In this example, the variable `t` will have the
       // type corresponding to its clause.
       whatAmI := func(i interface{}) {
              switch t := i.(type) {
              case bool:
                     fmt.Println("I'm a bool")
              case int:
                     fmt.Println("I'm an int")
              default:
                     fmt.Printf("Don't know type %T\n", t)
              }
       }
       whatAmI(true)
       whatAmI(1)
       whatAmI("hey")
}

Loops

// `for` is Go's only looping construct. Here are
// three basic types of `for` loops.

package main

import "fmt"

func main() {

       // The most basic type, with a single condition.
       i := 1
       for i <= 3 {
              fmt.Println(i)
              i = i + 1
       }

       // A classic initial/condition/after `for` loop.
       for j := 7; j <= 9; j++ {
              fmt.Println(j)
       }

       // `for` without a condition will loop repeatedly
       // until you `break` out of the loop or `return` from
       // the enclosing function.
       for {
              fmt.Println("loop")
              break
       }

       // You can also `continue` to the next iteration of
       // the loop.
       for n := 0; n <= 5; n++ {
              if n%2 == 0 {
                     continue
              }
              fmt.Println(n)
       }
}

 

Functions

// _Functions_ are central in Go. We'll learn about
// functions with a few different examples.

package main

import "fmt"

// Here's a function that takes two `int`s and returns
// their sum as an `int`.
func plus(a int, b int) int {

       // Go requires explicit returns, i.e. it won't
       // automatically return the value of the last
       // expression.
       return a + b
}

// When you have multiple consecutive parameters of
// the same type, you may omit the type name for the
// like-typed parameters up to the final parameter that
// declares the type.
func plusPlus(a, b, c int) int {
       return a + b + c
}

func main() {

       // Call a function just as you'd expect, with
       // `name(args)`.
       res := plus(1, 2)
       fmt.Println("1+2 =", res)

       res = plusPlus(1, 2, 3)
       fmt.Println("1+2+3 =", res)
}

 

Closures

Closures are like lambdas, in some languages.

// Anonymous functions are useful when you want to define
// a function inline without having to name it.

package main

import "fmt"

// This function `intSeq` returns another function, which
// we define anonymously in the body of `intSeq`. The
// returned function _closes over_ the variable `i` to
// form a closure.
func intSeq() func() int {
       i := 0
       return func() int {
              i += 1
              return i
       }
}

func main() {

       // We call `intSeq`, assigning the result (a function)
       // to `nextInt`. This function value captures its
       // own `i` value, which will be updated each time
       // we call `nextInt`.
       nextInt := intSeq()

       // See the effect of the closure by calling `nextInt`
       // a few times.
      //state of nect int is saved
       fmt.Println(nextInt())
       fmt.Println(nextInt())
       fmt.Println(nextInt())

       // To confirm that the state is unique to that
       // particular function, create and test a new one.
       newInts := intSeq()
       fmt.Println(newInts())
}

 

Struct in Golang

// Go's _structs_ are typed collections of fields.
// They're useful for grouping data together to form
// records.

package main

import "fmt"

// This `person` struct type has `name` and `age` fields.
type person struct {
       name string
       age  int
}

func main() {

       // This syntax creates a new struct.
       fmt.Println(person{"Bob", 20})

       // You can name the fields when initializing a struct.
       fmt.Println(person{name: "Alice", age: 30})

       // Omitted fields will be zero-valued.
       fmt.Println(person{name: "Fred"})

       // An `&` prefix yields a pointer to the struct.
       fmt.Println(&person{name: "Ann", age: 40})

       // Access struct fields with a dot.
       s := person{name: "Sean", age: 50}
       fmt.Println(s.name)

       // You can also use dots with struct pointers - the
       // pointers are automatically dereferenced.
       sp := &s
       fmt.Println(sp.age)

       // Structs are mutable.
       sp.age = 51
       fmt.Println(sp.age)
}

Method

// Go supports _methods_ defined on struct types.

package main

import "fmt"

type rect struct {
       width, height int
}

// This `area` method has a _receiver type_ of `*rect`.
func (r *rect) area() int {
       return r.width * r.height
}

// Methods can be defined for either pointer or value
// receiver types. Here's an example of a value receiver.
func (r rect) perim() int {
       return 2*r.width + 2*r.height
}

func main() {
       r := rect{width: 10, height: 5}

       // Here we call the 2 methods defined for our struct.
       fmt.Println("area: ", r.area())
       fmt.Println("perim:", r.perim())

       // Go automatically handles conversion between values
       // and pointers for method calls. You may want to use
       // a pointer receiver type to avoid copying on method
       // calls or to allow the method to mutate the
       // receiving struct.
       rp := &r
       fmt.Println("area: ", rp.area())
       fmt.Println("perim:", rp.perim())
}

Interfaces

// _Interfaces_ are named collections of method
// signatures.

package main

import "fmt"
import "math"

// Here's a basic interface for geometric shapes.
type geometry interface {
       area() float64
       perim() float64
}

// For our example we'll implement this interface on
// `rect` and `circle` types.
type rect struct {
       width, height float64
}
type circle struct {
       radius float64
}

// To implement an interface in Go, we just need to
// implement all the methods in the interface. Here we
// implement `geometry` on `rect`s.
func (r rect) area() float64 {
       return r.width * r.height
}
func (r rect) perim() float64 {
       return 2*r.width + 2*r.height
}

// The implementation for `circle`s.
func (c circle) area() float64 {
       return math.Pi * c.radius * c.radius
}
func (c circle) perim() float64 {
       return 2 * math.Pi * c.radius
}

// If a variable has an interface type, then we can call
// methods that are in the named interface. Here's a
// generic `measure` function taking advantage of this
// to work on any `geometry`.
func measure(g geometry) {
       fmt.Println(g)
       fmt.Println(g.area())
       fmt.Println(g.perim())
}

func main() {
       r := rect{width: 3, height: 4}
       c := circle{radius: 5}

       // The `circle` and `rect` struct types both
       // implement the `geometry` interface so we can use
       // instances of
       // these structs as arguments to `measure`.
       measure(r)
       measure(c)
}

 

These are some basic Golang codes, I just copied the examples and pointed to the link. This part if strictly for coders, who can program and a Golang refresher.

See you soon. Happy Coding.

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s