Data Types:
Go has three basic data types:
- bool: represents a boolean value and is either true or false
- Numeric: represents integer types, floating point values, and complex types
- string: represents a string value
Below is a example go code for different data types which also covers how the variables are declared and used in Go.
package main
import "fmt"
func main() {
// Method 1: var with type
var age int
age = 30
// Method 2: var with initialization (type inferred)
var name = "Mithran"
// Method 3: short declaration (inside functions only)
score := 95.5
// Multiple variables
var x, y int = 10, 20
a, b := "hello", true
// Different data types
var isActive bool = false
var price float64 = 19.99
var code byte = 'A' // alias for uint8
fmt.Println(name, age, score, x, y, a, b, isActive, price, code)
}
The above code provides the output as below
Mithran 30 95.5 10 20 hello true false 19.99 65
Variables:
Variables is a container to store a data value. Go uses call by value
There are two ways to declare/create variables as below
- With the var keyword: Use the var keyword, followed by variable name and type:
- var variable_name datatype = value
- var variable _name = value
- the above methods are recommend to be used.
- With the := sign: Use the := sign, followed by the variable value:
- variable_name := value
- to be used only for short declaration and that too inside functions only