In this part of our Go series, we'll delve into variables—a fundamental concept in any programming language. We'll cover variable declaration, types, and provide examples to illustrate how to use them effectively.
Variable Declaration
In Go, variables can be declared in several ways. Let's start with the most basic form.
1. Using the var
Keyword
The var
keyword is used for declaring variables in Go. Here's the syntax:
var variableName type
For example:
var name string
var age int
var isStudent bool
2. Short Variable Declaration
Go also supports a shorthand form of variable declaration using the :=
operator. This method infers the type of the variable from the value assigned to it.
name := "John"
age := 25
isStudent := true
Variable Types
Go is a statically typed language, meaning each variable has a type that is known at compile time. Let's look at the common types of variables in Go.
1. Basic Types
Integer Types:
int
,int8
,int16
,int32
,int64
,uint
,uint8
,uint16
,uint32
,uint64
Floating Point Types:
float32
,float64
Boolean Type:
bool
String Type:
string
Examples:
var a int = 10
var b float64 = 3.14
var c bool = true
var d string = "Hello, Go!"
2. Composite Types
- Array: Fixed-size collection of elements of the same type.
var arr [3]int = [3]int{1, 2, 3}
- Slice: Dynamic-size array.
var s []int = []int{1, 2, 3, 4, 5}
- Map: Collection of key-value pairs.
var m map[string]int = map[string]int{"foo": 1, "bar": 2}
- Struct: Collection of fields.
type Person struct {
Name string
Age int
}
var p Person = Person{Name: "Alice", Age: 30}
3. Pointers
Pointers hold the memory address of another variable.
var x int = 10
var ptr *int = &x
Examples and Usage
Let's combine these concepts in a few examples to demonstrate how variables are used in Go.
Example 1: Basic Variables
package main
import "fmt"
func main() {
var name string = "Alice"
age := 30
isStudent := false
fmt.Println("Name:", name)
fmt.Println("Age:", age)
fmt.Println("Is Student:", isStudent)
}
Example 2: Composite Types
package main
import "fmt"
func main() {
var arr [3]int = [3]int{1, 2, 3}
s := []int{4, 5, 6, 7, 8}
m := map[string]int{"apple": 2, "banana": 3}
fmt.Println("Array:", arr)
fmt.Println("Slice:", s)
fmt.Println("Map:", m)
}
Example 3: Structs and Pointers
package main
import "fmt"
type Person struct {
Name string
Age int
}
func main() {
var p Person = Person{Name: "Bob", Age: 25}
var ptr *Person = &p
fmt.Println("Person:", p)
fmt.Println("Pointer to Person:", ptr)
fmt.Println("Pointer dereferenced:", *ptr)
}
Conclusion
Understanding variables and their types is crucial for writing effective Go programs. By mastering variable declaration and types, you lay a strong foundation for more advanced topics. In the next part of this series, we'll explore Go's control structures and how to use them to control the flow of your programs.
Stay tuned and happy coding!
Next Part: User Input
Previous Part: Part 2: Setting Up Go on Windows 11