5. Variables
Different ways to define and initializing variables
var counter int
var name string
var(
counter int
name string
)
counter, name := 10, "Golang"
var x int ← Global
func main() {
x = 10 ← Global
fmt.Println(x)
function()
}
func function() {
// x = 4 ← Global
x := 5 ← Local
fmt.Println(x)
}
7. Control statement
if-else block
if x > 0 {
return y
}else{
return z
}
if with initialization:
x := 1
if r := x % 2; r == 0 {
fmt.Println("Even", r)
} else {
fmt.Println("Odd", r)
}
8. Control statement
For Loop:
for init; condition; post { } ← c like for loop
for condition { } ← while loop
for { } ← Endless loop
J: for j := 0; j < 5; j++ {
for i := 0; i < 10; i++ {
if i > 5 {
break J
}
println(i)
}
}
list := []string{"a", "b", "c", "d", "e", "f"}
for k, v := range list {
fmt.Println(k, v)
}
9. Control statement
Switch case:
● No break statement
● fallthrough keyword
● “,” as or for case statement.
i := 4
switch i {
case 0:
case 2:
case 4:
fallthrough
case 8:
fmt.Println("Even")
case 1, 3, 5, 7, 9:
fmt.Println("Odd")
default:
fmt.Println("???")
}
10. Type declaration
Array type:
var arr[10]int
a:= [3]int{1,2,3}
weekEnd:=[2]string{“saturday”, “sunday”}
c:=[2][2]int{[2]int{1,2},[2]int{3,4}}
11. Type declaration
Slice
sl := make([]int, 10)
a:=[...]int{1,2,3,4,5} //array
s1:=a[m:n]
m ← starting index
n ← last index n-1
n-m ← length
//copy, append
s0 := []int{0, 1, 3, 4}
s1 := append(s0, 5) //returns new slice
n:=copy(s1,s[0,4]) //copy within limits
12. Type declaration
Struct:
type Circle struct {
x, y, r float64
}
var c Circle
c := Circle{x: 0, y: 0, r: 5}
c := shape.Circle{0, 0, 5}
//Embedded types
type Shape struct {}
func (s *Shape) Draw() {
fmt.Println("Draw like shape")
}
type Circle struct {
x, y, r float64
Shape
}
13. Type declaration
Interface:
type doubleMaker interface {
double()
}
type intImplementer int
func (i intImplementer) double() {
fmt.Println(2 * i)
}
//Embedded types
type tripleMaker interface {
triple()
}
type doubleMaker interface {
tripleMaker
double()
}
15. Goroutines and channels
Code sample..
ready(“tea”,1) ← normal function call
go ready(“tea”,1) ← started as goroutine
ci := make(chan int) ← unbuffered channel of integers
cj := make(chan int, 0) ← unbuffered channel of integers
cs := make(chan int, 100) ← buffered channel of integers