Here we explore Go data types, understand basic and advanced data types and use the same in programs with examples.
1. Numeric Data Types
Integers:
Go provides various sizes of integers, such as int
, int8
, int16
, int32
, and int64
. Similarly, there are unsigned integer types like uint
, uint8
, uint16
, uint32
, and uint64
.
package main
import "fmt"
func main() {
var num int = 42
var unsignedNum uint = 42
fmt.Println("Integer:", num)
fmt.Println("Unsigned Integer:", unsignedNum)
}
Floating-Point Numbers:
Go supports two floating-point types: float32
and float64
.
package main
import "fmt"
func main() {
var num1 float32 = 3.14
var num2 float64 = 3.14159265359
fmt.Println("Float32:", num1)
fmt.Println("Float64:", num2)
}
2. String Data Type
Strings in Go are sequences of characters. They are immutable, meaning once a string is created, it cannot be changed.
package main
import "fmt"
func main() {
greeting := "Hello, "
name := "John"
concatenated := greeting + name
fmt.Println("Concatenated String:", concatenated)
fmt.Println("Length of String:", len(concatenated))
fmt.Println("Character at index 2:", string(concatenated[2]))
}
3. Boolean Data Type
Boolean data types represent truth values: true
or false
.
package main
import "fmt"
func main() {
var isTrue bool = true
var isFalse bool = false
fmt.Println("isTrue:", isTrue)
fmt.Println("isFalse:", isFalse)
}
4. Complex Data Type
Go supports complex numbers with complex64
and complex128
types.
package main
import "fmt"
func main() {
var complexNum1 complex64 = 3 + 4i
var complexNum2 complex128 = 2 - 6i
sum := complexNum1 + complexNum2
fmt.Println("Complex Number 1:", complexNum1)
fmt.Println("Complex Number 2:", complexNum2)
fmt.Println("Sum of Complex Numbers:", sum)
}
5. Array, Slice, and Map
Array:
Arrays in Go have a fixed size. The size is part of the array's type.
package main
import "fmt"
func main() {
// Array
var numbers [3]int
numbers[0] = 1
numbers[1] = 2
numbers[2] = 3
fmt.Println("Array:", numbers)
}
Slice:
Slices are more flexible than arrays. They are dynamically sized and reference a contiguous portion of an underlying array.
package main
import "fmt"
func main() {
// Slice
numbers := []int{1, 2, 3, 4, 5}
// Slicing
slice1 := numbers[1:3]
fmt.Println("Original Slice:", numbers)
fmt.Println("Sliced Slice:", slice1)
}
Map:
Maps are key-value pairs and are unordered collections.
package main
import "fmt"
func main() {
// Map
person := map[string]string{
"name": "John",
"age": "30",
"city": "New York",
}
// Adding a new key-value pair
person["occupation"] = "Developer"
fmt.Println("Person:", person)
}
These examples demonstrate the usage of various data types in Go, including numeric types, strings, booleans, complex numbers, arrays, slices, and maps. Understanding these data types and their characteristics is crucial for effective Go programming.