DataTypes:
1. Numeric Types:
- int8, int16, int32, int64, int
- uint8, uint16, uint32, uint64, uint
- float32, float64
- complex64, complex128
- byte
- rune
2. bool
3. string
Declaration & Initialization:
var name string = "GoBot" var salary int = 1000 var zipcode int var trueVal = true
Type Inference:
If you pass an initial value, Go will automatically be able to infer the type of the variable using initial value as in examples below:
var name = "GoBot" var salary = 1000 city := "San Francisco" var a, b int = 5, 7 var x, y = "Hello", 2 fmt.Println(name, salary, city, a, b, x, y)
Notice the ':=' syntax in line 4 which is shorthand for declaring and initializing variable which is similar to writing ' var city string = "San Francisco" '
*- shorthand notation requires initial values for all variables on the left-hand side of the assignment
*- shorthand notation can only be used when one of the variables on the left side of the assignment is newly declared, see the examples below:
Works:
a, b := 1, 2 fmt.Println("a -> ", a, "b -> ", b) b, c := 7, 9 // c is new fmt.Println("b -> ", b, "c -> ", c)
Error:
a, b := 7, 8 fmt.Println("a ->", a, "b ->", b) a, b := 12, 17 //error because of no new variables
Also, you can declare multiple variables with different types as in below:
var ( street = "chestnut" apartment int zipcode = 94129 city string )
Type Conversion:
In Go, there is no automatic type promotion or conversion so you have to explicitly convert the type to perform an operation on different types or assign a variable of one type to another.
Error:
func main() { x := 10 y := 12.5 sum := x + y //Error: invalid operation (mismatched types int and float64) fmt.Println(sum) }
Works:
func main() { x := 10 y := 12.5 sum := x + int(y) //Fixed by converting y to int fmt.Println(sum) }
Happy Coding 🤖
Comments
Post a Comment