Go Tutorial Part 2 - Variables
Contents
1 Simple Variable Definition and initilization
package main
import "fmt"
func main() {
var card string = "Ace of Spades"
fmt.Println(card)
}
- var: used to create anew ariable
- card: the name of the variable
- string: type of the variable
- “Ace of Spades”: value of the variable
2 Supported Data Types:
- bool: true, false
- string “Hi”, Hello"
- int: 0, -1000, 900
- float64: 10.00001, 0.0009, -1.111
- and many more…
3 Alternative Type Definition
package main
import "fmt"
func main() {
card := "Ace of Spades"
card = "Five of Diamonds"
fmt.Println(card)
}
No need to define type, it is inferred if “:=” is used
4 Initialize then Assign
package main
import "fmt"
func main() {
var deckSize int
deckSize = 52
fmt.Println(deckSize)
}
5 We can initialize a variable outside of a function, we just can’t assign a value to it.
package main
import "fmt"
var deckSize int
func main() {
deckSize = 50
fmt.Println(deckSize)
}
6 Each Variable declared must always be used
Type conversion
greeting := "Hi There"
fmt.Println([]bytr(greetin))