Back to: Golang
A variable is a named memory location that stores a value of a specific data type. Variables are used to hold data that may change during the execution of a program. Let’s see how we use variables in Golang:
Golang uses a static type system, which means that each variable must be declared with a specific type before it can be used. To declare a variable in Golang, use the following syntax:
var variable_name data_type
For example, to declare a variable called “age” of type “int”, you would write:
var age int
You can also initialize a variable at the time of declaration by assigning a value to it:
var name string = "John"
In some cases, Golang can infer the type of a variable based on the assigned value, in which case you can omit the type declaration:
age := 42
Once a variable is declared, you can assign new values to it as needed:
age = 43
You can also declare and assign multiple variables at once using the following syntax:
var x, y, z int = 1, 2, 3
Code example of how to declare and use variables in Golang:
package main
import "fmt"
func main() {
// Declare a variable called "age" of type "int"
var age int
// Assign a value of 42 to the "age" variable
age = 42
// Declare and initialize a variable called "name" of type "string"
var name string = "John"
// Declare and initialize multiple variables at once
var x, y, z int = 1, 2, 3
// Golang can infer the type of a variable based on the assigned value
greeting := "Hello, world!"
// Print the values of the variables
fmt.Println("Age:", age)
fmt.Println("Name:", name)
fmt.Println("x:", x, "y:", y, "z:", z)
fmt.Println(greeting)
}
In this example, we declare a variable called “age” of type “int” and assign a value of 42 to it. We also declare and initialize a variable called “name” of type “string” and multiple variables at once. Additionally, we use Golang’s type inference to declare a variable called “greeting” and assign it a value of “Hello, world!”.
Follow us on social media
Follow Author