Introduction
Variables are fundamental in any programming language, and Go is no exception. In this guide, we'll explore how variables work in Go, along with the various data types available.
Declaring Variables
In Go, you declare a variable using the var
keyword. Here's a simple example:
package main
import "fmt"
func main() {
var age int
age = 30
fmt.Println("My age is", age)
}
In this code, we declare a variable named age
with the type int
and assign it the value 30
.
Data Types in Go
Go has various built-in data types, including integers, floating-point numbers, strings, and more. Here are some common data types in Go:
int
: Signed integers (e.g.,int
,int8
,int16
,int32
,int64
).float64
: 64-bit floating-point numbers.string
: Textual data.bool
: Boolean values (eithertrue
orfalse
).
Here's an example of declaring variables with different data types:
package main
import "fmt"
func main() {
var age int
var height float64
var name string
var isStudent bool
age = 30
height = 175.5
name = "John Doe"
isStudent = true
fmt.Println("Name:", name)
fmt.Println("Age:", age)
fmt.Println("Height:", height)
fmt.Println("Is Student:", isStudent)
}
Type Inference
In many cases, Go can infer the type of a variable from the value you assign to it. This is known as type inference. For example:
package main
import "fmt"
func main() {
name := "Alice"
age := 25
isStudent := false
fmt.Println("Name:", name)
fmt.Println("Age:", age)
fmt.Println("Is Student:", isStudent)
}
In this code, we didn't explicitly specify the variable types. Go inferred them from the assigned values.
Constants
Constants are variables whose values cannot be changed once they are set. In Go, you can declare constants using the const
keyword. Here's an example:
package main
import "fmt"
const pi = 3.14159
func main() {
fmt.Println("The value of pi is", pi)
}
Further Resources
To continue learning about Go variables and data types, explore the following resources:
- Go Tour - Basics - An interactive online tutorial for learning Go.
- Effective Go - Variables - Official Go documentation on variables.