Data Types in Go

In Go (Golang), data types are used to specify the type of values that variables can hold or functions can return. Go is a statically-typed language, which means that you must explicitly declare the data type of a variable when you define it. The data types in Go can be categorized into several basic categories:

  1. Numeric Types:
    • int: Signed integers that can hold positive and negative whole numbers (e.g., -10, 0, 42).
    • uint: Unsigned integers that can only hold non-negative whole numbers (e.g., 0, 42).
    • float32, float64: Floating-point numbers with single and double precision (e.g., 3.14, 2.718).
    • complex64, complex128: Complex numbers with single and double precision (e.g., 2+3i, 1.5-2i).

Example:

package main

import "fmt"

func main() {
    var age int = 30
    var pi float64 = 3.14159
    var complexNum complex128 = 2 + 3i

    fmt.Println("Age:", age)
    fmt.Println("Pi:", pi)
    fmt.Println("Complex Number:", complexNum)
}
  1. String Type:
    • string: A sequence of characters representing text.

Example:

package main

import "fmt"

func main() {
    message := "Hello, Go!"

    fmt.Println(message)
}
  1. Boolean Type:
    • bool: Represents true or false values.

Example:

package main

import "fmt"

func main() {
    var isGoAwesome bool = true

    fmt.Println("Is Go awesome?", isGoAwesome)
}
  1. Composite Types:
    • array: Fixed-size collection of elements with the same type.
    • slice: Dynamic-size collection that is based on an array.
    • map: Unordered collection of key-value pairs.
    • struct: Custom data type that groups together different fields of different types.

Example:

package main

import "fmt"

func main() {
    // Array
    var numbers [3]int
    numbers[0] = 10
    numbers[1] = 20
    numbers[2] = 30

    // Slice
    fruits := []string{"apple", "banana", "orange"}

    // Map
    scores := map[string]int{
        "Alice": 85,
        "Bob":   92,
        "Eve":   78,
    }

    // Struct
    type Person struct {
        Name string
        Age  int
    }

    person1 := Person{Name: "John", Age: 30}

    fmt.Println("Array:", numbers)
    fmt.Println("Slice:", fruits)
    fmt.Println("Map:", scores)
    fmt.Println("Struct:", person1)
}
  1. Pointer Type:
    • *: Represents the memory address of a variable.

Example:

package main

import "fmt"

func main() {
    var number int = 42
    var ptr *int

    ptr = &number

    fmt.Println("Value of number:", number)
    fmt.Println("Address of number:", &number)
    fmt.Println("Value of pointer:", ptr)
}

These are the basic data types in Go, and they allow you to represent and manipulate different types of data in your programs. Understanding data types is essential for writing correct and efficient Go code, as it helps ensure that variables hold the appropriate data and that operations are performed correctly.