In this Tutorial-:
Introduction
Variables and constants are crucial elements in any programming language, including Go. They allow programmers to store and manipulate data during the execution of a program.
In this tutorial, we’ll explore variables and constants in Go, understand their differences, and learn how to use them effectively in your Go programs.
Variables in Go
In Go, variables are used to store and represent data of various types, such as numbers, strings, and more. They allow us to store values that can be modified during the program’s execution. To declare a variable, we use the syntax:
var variableName dataType
Here’s an example of declaring and using variables in Go:
package main
import "fmt"
func main() {
var age int
age = 30
var name string = "John"
height := 175.5
fmt.Println("Name:", name)
fmt.Println("Age:", age)
fmt.Println("Height:", height)
}
In this example, we declared variables age, name, and height, and assigned values to them.
O/P
Name: John
Age: 30
Height: 175.5
Constants in Go
Unlike variables, constants hold values that cannot be changed once assigned. They are useful for storing fixed values that remain constant throughout the program’s execution. To declare a constant, we use the syntax:
const constantName dataType = value
Here’s an example of declaring and using constants in Go:
package main
import "fmt"
func main() {
const pi float64 = 3.14159
const daysInWeek int = 7
fmt.Println("PI:", pi)
fmt.Println("Days in a week:", daysInWeek)
}
O/P
PI: 3.14159
Days in a week: 7
In this example, we declared constants pi and daysInWeek.
Type Inference
In Go, you can use type inference to declare variables without explicitly specifying their datatype. The Go compiler automatically infers the datatype based on the assigned value. Here’s an example:
package main
import "fmt"
func main() {
age := 30
name := "John"
height := 175.5
fmt.Println("Name:", name)
fmt.Println("Age:", age)
fmt.Println("Height:", height)
}
O/P
Name: John
Age: 30
Height: 175.5
Initializing Multiple Variables in one go
In Go, you can initialize multiple variables in a single line using the short variable declaration := or the var keyword. The syntax for initializing multiple variables at once is as follows:
var variable1, variable2, variable3 dataType = value1, value2, value3
OR
variable1, variable2, variable3 := value1, value2, value3
Variables and constants are essential components of Go programming, allowing developers to store and manipulate data effectively. In this guide, we explored variables and constants in Go, their differences, and how to declare and use them in your programs. Armed with this knowledge, you can confidently work with variables and constants, enabling you to create powerful and flexible Go applications.