Programmers now have the power to "declare war", thanks to variables. I'll show you how in this read.
Variables are fundamental in Go and they are used to store data that is used throughout the program.
Declaring Variables
1.
Declare war(variable name) using var
key word:
package main
func main(){
//War will be given an empty string ("")
var war string
}
2.
Next, assign "Battle field" to war variable.
package main
func main(){
var war string
war = "battlefield"
}
3.
Multiple variables:
package main
func main(){
var war weapon enemy string
}
4.
Constant:
const
keyword is used for variables with fixed values.
const can be declared inside and outside of a function.
package main
import ("fmt")
const PI = 3.14
func main() {
fmt.Println(PI)
}
Shorthand Syntax
With this syntax, Go is able to determine war's
data type depending on the value we set to war
.
package main
func main(){
// type int
war := 3
// type string
war := "battle field"
}
Go data types
string
- stores string ("John", "Doe")
int
- stores integer (1,2,3)
float64
- Stores floating point numbers(1.4, 4.5)
bool
- stores true or false values
Variable Naming rules
Variables must start with a letter or underscore and can contain letters, digits and underscores.
Go is case sensitive: str
and Str
are two different variables.
Use descriptive names. e.g wordCount
instead of wc
Conclusion
Remember variables are like labeled containers that hold values. You have to master them to be an effective programmer.
Top comments (2)
Informative
Nice.