Go, a statically typed language, offers a variety of data types to represent different kinds of values. Understanding these types is crucial for effective Go programming.
Go provides several numeric types for integers and floating-point numbers:
The boolean type in Go is represented by bool
, which can be either true
or false
.
Strings in Go are immutable sequences of bytes, typically representing text. They are enclosed in double quotes.
Arrays in Go have a fixed size and contain elements of the same type. They are declared using square brackets.
Slices are dynamic, resizable views into arrays. They are more flexible than arrays and are commonly used in Go programs. Learn more about Go Slices.
Maps are Go's built-in associative data type, also known as hash tables or dictionaries in other languages. Explore Go Maps for detailed information.
Structs are composite types that group together variables under a single name. They are used to represent records or custom data types. Dive deeper into Go Structs.
package main
import "fmt"
func main() {
var i int = 42
var f float64 = 3.14
var b bool = true
var s string = "Hello, Go!"
fmt.Printf("Integer: %d\nFloat: %f\nBoolean: %t\nString: %s\n", i, f, b, s)
}
package main
import "fmt"
func main() {
// Array
var arr [3]int = [3]int{1, 2, 3}
// Slice
slice := []int{4, 5, 6}
// Map
m := map[string]int{"one": 1, "two": 2}
// Struct
type Person struct {
Name string
Age int
}
p := Person{Name: "Alice", Age: 30}
fmt.Printf("Array: %v\nSlice: %v\nMap: %v\nStruct: %+v\n", arr, slice, m, p)
}
Go supports type inference, allowing you to omit the type declaration in many cases. The compiler will automatically deduce the type based on the value assigned.
In Go, variables declared without an explicit initial value are given their zero value:
Go requires explicit type conversions. There are no automatic type promotions or conversions between different types.
Understanding Go's data types is fundamental to writing efficient and correct Go programs. As you progress, explore more advanced concepts like Go Pointers and Go Interfaces to leverage the full power of Go's type system.