DEV Community

Emmanuel Barsu
Emmanuel Barsu

Posted on

Variables in Go

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
}
Enter fullscreen mode Exit fullscreen mode

2.
Next, assign "Battle field" to war variable.

package main

func main(){
var war string
war = "battlefield"
}
Enter fullscreen mode Exit fullscreen mode

3.
Multiple variables:

package main

func main(){

var war weapon enemy string 
}
Enter fullscreen mode Exit fullscreen mode

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)
}
Enter fullscreen mode Exit fullscreen mode

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"
}
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
moseeh_52 profile image
moseeh

Informative

Collapse
 
vomolo profile image
vomolo

Nice.