Go, also known as Golang, is a statically typed, compiled language known for its simplicity and efficiency. In this article, we’ll explore the basic types in Go and provide clear code examples to illustrate their usage.

Basic Types Overview

Go has several basic types including:

  • Numeric types: integer and floating point types
  • Strings: UTF-8 encoded text
  • Boolean: true or false values

Integer Types

Go supports several integer types based on bit size and whether you want them signed or unsigned:

  • int and uint
  • int8, int16, int32, int64
  • uint8, uint16, uint32, uint64

Basic Example

package main

import "fmt"

func main() {
    var a int = 10
    var b uint = 20
    fmt.Println("int: ", a)
    fmt.Println("uint: ", b)
}

Signed vs Unsigned

package main

import "fmt"

func main() {
    var c int16 = -250
    var d uint16 = 300
    fmt.Println("int16: ", c)
    fmt.Println("uint16: ", d)
}

Floating Point Types

Go provides two floating-point types: float32 and float64, which differ by precision.

Basic Example

package main

import "fmt"

func main() {
    var e float32 = 3.14
    var f float64 = 6.28
    fmt.Println("float32: ", e)
    fmt.Println("float64: ", f)
}

String Type

Strings in Go are UTF-8 encoded sequences of bytes. You can create a string with double quotes:

Basic Example

package main

import "fmt"

func main() {
    greeting := "Hello, Go!"
    fmt.Println(greeting)
}

Boolean Type

Booleans in Go are simple and are used to represent true or false values.

Basic Example

package main

import "fmt"

func main() {
    var status bool = true
    fmt.Println("Status: ", status)
}

Advanced Example

Here's a more complex example that demonstrates using multiple types together:

package main

import "fmt"

func main() {
    var age int = 30
    var pi float64 = 3.14159265359
    var name string = "John Doe"
    var isActive bool = true

    fmt.Printf("Name: %s, Age: %d\n", name, age)
    fmt.Printf("Value of Pi: %f\n", pi)
    fmt.Printf("Active: %t\n", isActive)
}

By understanding these basic types, you'll be better equipped to write effective Go programs that make efficient use of memory and processing power.