
Data Types in GoLang
GoLang provides a wide variety of data types, which can be categorized into four major groups: basic types, aggregate types, reference types, and interface types.
1. Basic Data Types
These are the fundamental data types in Go.
Numeric Types
-
Integer Types:
- Signed Integers:
- int (platform-dependent, typically 32 or 64 bits)
- int8, int16, int32, int64
- Unsigned Integers:
- uint (platform-dependent)
- uint8, uint16, uint32, uint64
- byte (alias for uint8)
- Signed Integers:
-
Floating-Point Numbers:
- float32, float64
-
Complex Numbers:
- complex64 (real and imaginary parts as float32)
- complex128 (real and imaginary parts as float64)
-
Other Numeric Types:
- rune (alias for int32, represents Unicode code points)
Boolean
- bool
- Values: true or false.
String
- string
- Represents a sequence of bytes (characters).
- Immutable in Go.
2. Aggregate Types
-
Array:
- Fixed-size collection of elements of the same type.
var arr [5]int
- Fixed-size collection of elements of the same type.
-
Slice:
- Dynamically-sized, flexible view into an array.
var slice []int slice = append(slice, 10)
- Dynamically-sized, flexible view into an array.
-
Struct:
- Collection of fields.
type Person struct { Name string Age int }
- Collection of fields.
3. Reference Types
-
Pointer:
- Stores the memory address of a value.
var ptr *int
- Stores the memory address of a value.
-
Function:
- Functions are first-class citizens in Go and can be assigned to variables or passed as arguments.
-
Map:
- Key-value pairs, similar to dictionaries in Python.
var m map[string]int
- Key-value pairs, similar to dictionaries in Python.
-
Channel:
- Used for communication between goroutines.
var ch chan int
- Used for communication between goroutines.
4. Interface Types
- Define a set of methods that a type must implement.
type Shape interface { Area() float64 }
Type Conversion
Go is strictly typed, so explicit conversion is required between types.
var a int = 10 var b float64 = float64(a)
Example Usage
package main import "fmt"
func main() {
var age int = 25
var price float64 = 19.99
var name string = "GoLang"
var active bool = true
fmt.Println("Name:", name)
fmt.Println("Age:", age)
fmt.Println("Price:", price)
fmt.Println("Active:", active)
}
If you'd like a deeper dive into a specific type, let me know!