SyntaxStudy
Sign Up
Go Basic Types and Type Conversions
Go Beginner 1 min read

Basic Types and Type Conversions

Go is a statically typed language, meaning every variable has a fixed type known at compile time. The built-in numeric types include int, int8, int16, int32, int64, uint and their unsigned counterparts, as well as float32 and float64 for floating-point numbers. The `int` type is platform-dependent (32 or 64 bits), while the sized variants guarantee a specific width. Unlike many languages, Go does not perform implicit type conversions. You must explicitly convert between compatible types using the type name as a conversion function, for example `float64(x)` or `int(y)`. This strictness prevents subtle bugs caused by unexpected implicit widening or narrowing of values. Strings in Go are immutable sequences of bytes encoded in UTF-8. The `rune` type (an alias for int32) represents a Unicode code point, which is important when iterating over strings that may contain multi-byte characters. Use `[]rune(s)` to work with individual Unicode characters and `[]byte(s)` when you need raw byte access.
Example
package main

import (
    "fmt"
    "math"
    "unicode/utf8"
)

func main() {
    // Integer types
    var i   int   = 42
    var i64 int64 = 100

    // Explicit conversion required
    sum := i + int(i64)
    fmt.Println("sum:", sum)

    // Float operations
    var f float64 = math.Sqrt(2)
    fmt.Printf("sqrt(2) = %.6f\n", f)

    // float64 -> int truncates (does NOT round)
    fmt.Println("int(f):", int(f))

    // String and runes
    s := "Hello, 世界"
    fmt.Println("bytes :", len(s))
    fmt.Println("runes :", utf8.RuneCountInString(s))

    for i, r := range s {
        fmt.Printf("index=%d rune=%c code=%d\n", i, r, r)
    }

    // byte slice round-trip
    b := []byte(s)
    s2 := string(b)
    fmt.Println("round-trip:", s2)

    // Boolean
    var flag bool = true
    fmt.Println("flag:", flag, "!flag:", !flag)
}