Introduction to Golang
Basics
Packages
- Programs start running with package main
package main
import "fmt"
func main(){
fmt.Println("Hello World")
}
- Multiple package import paths.
package main
import (
"fmt"
"math/rand"
)
func main(){
fmt.Println("Fav number:", rand.Intn(10))
}
- Exported Names
Exported names start with capital letter,just like
Pi
inmath
package.
package main
import (
"fmt"
"math"
)
func main(){
fmt.Println(math.Pi)
}
Functions
- Functions can take zero or more arguments, variable type comes after variable name.
package main
import "fmt"
func multiply(x int,y int) int {
return x*y
}
func main(){
fmt.Println(multiply(4,2))
}
- Shortening function parameters,for better readability.
func multiply(x,y int) int {
return x*y
}
- Return multiple results in a function definition
func addsub(x,y int) (int,int){
return x+y,x-y)
}
func main(){
fmt.Println(addsub(20,20))
}
- Named return values.
func addsub(x,y int) (add,sub int) {
add = x+y
sub = x-y
return
}
- Multiple Returns
func swap(x,y string) (string,string){
return y,x
}
func addsub(x,y int) (int,int){
return x+y,x-y
}
func main(){
fmt.Println(swap("hello","world")
fmt.Pritln(addsub(10,20))
}
- Variables
package main import "fmt" var hello bool var i int=0 func main(){ var b,c int= 20,30 fmt.Println(i,hello,b,c) }
Short variable description
k:=3
Types
- Basic Types
- Integers - Signed (int,int8,int16,int32,int64) Unsigned (uint,uint8,uint16,uint32,uint64)
- Floats - float32,float64
- Complex Numbers - float32,float64
- Byte
- Rune
- String
- Rune
- Boolean
- Composite Types
- Collections/Aggregation - Arrays,Structs
- Reference Types - slices, maps,channels, pointers,functionos
- Interface
package main
import (
"fmt"
"math/cmplx"
)
var (
hello bool = false
name string = "vinay"
age int = 22
z complex128 = cmplx.Sqrt(-5+2i)
)
func main(){
fmt.Printf("Type: %T Value: %v\n",hello,hello)
fmt.Printf("Type: %T Value: %v",name,name)
fmt.Printf("Type: %T Value: %v",age,age)
fmt.Printf("Type: %T Values: %v",z,z)
}
//observe the printf not the usual Println
Type conversion and type inference
package main
import "fmt"
import "math"
// The expression T(v) converts the value v to the type T.
func main(){
// Type conversion
var x,y int =3,5
var f float64 = math.Sqrt(float64(x*x + y*y))
var z uint = uint(f)
fmt.Println(x,y,z)
fmt.Printf("Type: %T Value: %v\n",x,x)
fmt.Printf("Type: %T Value: %v\n",z,z)
fmt.Printf("Type: %T Value: %v\n",f,f)
// Type Inference - the variable's type is inferred without from the value
// on the right side
i:=22
fmt.Printf("Type: %T Values: %v",i,i)
}
Constants
package main
import "fmt"
func main(){
const Pi = 3.14
// never use short description for constants i.e :=
fmt.Println(Pi)
}