Variables: Types
Here are the main types you need to know:
Boolean
var isTrue bool = true
var isFalse bool = false
Numeric
var age int = 25
var price float64 = 19.99
String
var name string = "John"
var message string = "Hello, World!"
Array
var numbers [3]int = [3]int{1, 2, 3}
var names [2]string = [2]string{"John", "Jane"}
// Accessing elements
fmt.Println(numbers[0]) // Output: 1
fmt.Println(names[1]) // Output: Jane
// Changing elements
numbers[2] = 4
names[1] = "Doe"
// Iterating over array
for i, number := range numbers {
fmt.Println(i, number)
}
// This will print:
// 0 1
// 1 2
// 2 4
Map
var person map[string]string = map[string]string{"name": "John", "age": "25"}
// Adding a new element
person["name"] = "Jane"
person["age"] = "26"
// Deleting an element
delete(person, "age")
// Iterating over map
for key, value := range person {
fmt.Println(key, value)
}
// This will print:
// name Jane
// age 26
Struct
type Person struct {
Name string
Age int
}
var person Person = Person{Name: "John", Age: 25}
// Accessing fields
fmt.Println(person.Name) // Output: John
fmt.Println(person.Age) // Output: 25
// Changing fields
person.Name = "Jane"
person.Age = 26
// Iterating over struct
for key, value := range person {
fmt.Println(key, value)
}
// This will print:
// Name: Jane
// Age: 26
Slice
var numbers []int = []int{1, 2, 3}
Difference between Array and Slice:
- Array has a fixed size
- Slice is dynamic and can grow or shrink
Function
func add(a int, b int) int {
return a + b
}
Pointer
Pointer is a variable that stores the memory address of another variable.
var a int = 10
var b *int = &a // b is a pointer to a
We’ll cover more about functions and pointers in one of the future posts.
Type Conversion
Type conversion is the process of converting a variable from one type to another.
var a int = 10
var b float64 = float64(a) // b is now 10.0
Type Switch
Type switch is a construct that permits several type assertions in series.
var a interface{} = "Hello, World!"
switch a.(type) {
case string:
fmt.Println("a is a string")
}
Conclusion
Understanding Go’s type system and choosing the appropriate type for each use case is crucial for writing efficient and maintainable Go code.