0

Quick introduction to Go/Golang

Reading Time: 2 minutes

Basic Types

  • bool
  • string
  • int, int8, int16, int32, int64
  • unit, unit8, unit16, unit32, unit64 uintptr
  • byte //alias for uint8
  • rune //alias for int32
  • float32, float64
  • complex64, complex128

Initial values

  • false for bool
  • 0 (zero) for numeric types
  • “” (empty string) for string

Variable definition & declaration

var i int =120

or

i := 120

Multiple variable declaration

var i, j int = 1, 2

var a, b string = "hi", "bye"

Type conversion

var i int = 300

var f float64 = float64(i)

Constants

const Pi = 3.14

Array

var intArray = []int{100, 200, 300}

Function

  • A function can take zero or more arguments
  • A function can also return zero or more results
  • Parameters passed to the function is by default it is value type
func add(a int, b int) int {
  return x + y
}

function myLocation() (longitude, latitude) {
  longitude = 123.23
  latitude = 321.55
  return
}

Flow control

Go has only one looping keyword for used for and while looping

For

package main

import "fmt"

func main(){
  sum:=0
  for i:=0; i<10; i++ {
    sum+=i
  }
  fmt.Println(sum);
}

while using for

package main
import "fmt"

func main(){
  sum:=0
  i:=9
  for i&amp;amp;amp;gt;-1 {
    sum+=i
    i++
  }
  fmt.Println(sum);
}

for on array


package mainpackage main
import "fmt"
var intArray = []int{100, 200, 300}
func main() {
  for index, value := range intArray { 
    fmt.Println(index, value) 
  }
}

if else


var i int = 10

if i<5{

fmt.Println("Its lesser than 5")

}

else{

fmt.Println("Its not less than 5")

}

switch


language := "golang"

switch language{

case "golang":

fmt.Println("Its golang")

case "c#":

fmt.Println("Its C#");

default:

fmt.Println("Its something else")

}

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.