Golang Basic 2 - Basic Data Types && Variable
Basic Data Types
- int, eg. 0, 1, 2, 3.
- float32, float64, eg. 3.14159.
- string, eg. "Hello World".
- bool, eg. true, false.
- rune, eg. 'a', 'b'. (char, saved as int)
Variable
Declear variable
var VariableName DataType
Set value
VariableName = Value
Sample
usr@host:go/ # cat l2s1.go
package main
import (
"fmt"
)
func main(){
// declear variables
var int_val int // declear an int variable
var float_val float64 // declear a float variable
var string_val string // declear a string variable
var bool_val bool // declear a bool variable
var rune_val rune // declear a rune variable
// set value for variables
int_val = 3
float_val = 1.234
string_val = "Hello"
bool_val = true
rune_val = 'A'
// print them
fmt.Println(int_val)
fmt.Println(float_val)
fmt.Println(string_val)
fmt.Println(bool_val)
fmt.Println(rune_val)
}
usr@host:go/ # go build l2s1.go
usr@host:go/ # ./l2s1
3
1.234
Hello
true
65
Declear && Set value at the same time
var VariableName DataType = Value
Sample
usr@host:go/ # cat l2s2.go
package main
import (
"fmt"
)
func main(){
// declear and set variables
var int_val int = 3
var float_val float64 = 1.234
var string_val string = "Hello"
var bool_val bool = true
var rune_val rune = 'A'
// print them
fmt.Println(int_val)
fmt.Println(float_val)
fmt.Println(string_val)
fmt.Println(bool_val)
fmt.Println(rune_val)
}
usr@host:go/ # go build l2s2.go
usr@host:go/ # ./l2s2
3
1.234
Hello
true
65
Change values in variable
usr@host:go/ # cat l2s3.go
package main
import (
"fmt"
)
func main(){
// declear and set variable
var int_val int = 3
// print them
fmt.Println(int_val)
// set new value for variable
int_val = 5
// print them
fmt.Println(int_val)
}
usr@host:go/ # go build l2s3.go
usr@host:go/ # ./l2s3
3
5
Some errors
usr@host:go/ # cat l2s4.go
package main
import (
"fmt"
)
func main(){
// declear and set variable
var int_val int = 3
// print them
fmt.Println(int_val)
// set new value for variable
int_val = "abc"
// print them
fmt.Println(int_val)
}
usr@host:go/ # go build l2s4.go
# command-line-arguments
./l2s4.go:15:15: cannot use "abc" (type string) as type int in assignment
- The values we set for the variable must match the data type.
Related
Be First to Comment