Skip to main content
โšก Calmops

Go Variables and Data Types Fundamentals

Go Variables and Data Types Fundamentals

Go’s type system is one of its defining features. Understanding variables and data types is essential for writing effective Go code.

Variable Declaration

Basic Variable Declaration

package main

import "fmt"

func main() {
    // Explicit type declaration
    var name string = "Alice"
    var age int = 30
    var height float64 = 5.8
    var active bool = true

    fmt.Println(name, age, height, active)
}

Type Inference

package main

import "fmt"

func main() {
    // Type inference - compiler determines type
    var name = "Bob"           // string
    var count = 42             // int
    var price = 19.99          // float64
    var enabled = true         // bool

    fmt.Printf("%T\n", name)   // string
    fmt.Printf("%T\n", count)  // int
}

Short Variable Declaration

package main

import "fmt"

func main() {
    // Short declaration (only inside functions)
    name := "Charlie"
    age := 25
    score := 95.5

    fmt.Println(name, age, score)

    // Multiple assignments
    x, y := 10, 20
    fmt.Println(x, y)

    // Blank identifier for unused values
    _, err := someFunction()
}

Data Types

Numeric Types

package main

import "fmt"

func main() {
    // Signed integers
    var i8 int8 = 127
    var i16 int16 = 32767
    var i32 int32 = 2147483647
    var i64 int64 = 9223372036854775807

    // Unsigned integers
    var u8 uint8 = 255
    var u16 uint16 = 65535
    var u32 uint32 = 4294967295
    var u64 uint64 = 18446744073709551615

    // Platform-dependent
    var i int = 42           // 32 or 64 bits
    var u uint = 42          // 32 or 64 bits
    var r rune = 'A'         // int32, represents Unicode code point
    var b byte = 255         // uint8

    // Floating point
    var f32 float32 = 3.14
    var f64 float64 = 3.14159265359

    // Complex numbers
    var c64 complex64 = 1 + 2i
    var c128 complex128 = 3 + 4i

    fmt.Println(i8, f64, c128)
}

String and Boolean Types

package main

import "fmt"

func main() {
    // Strings
    var str string = "Hello, Go!"
    var multiline string = `This is a
    multiline string`

    // Booleans
    var isActive bool = true
    var isDeleted bool = false

    fmt.Println(str)
    fmt.Println(isActive, isDeleted)
}

Zero Values

package main

import "fmt"

func main() {
    // Variables declared without initialization get zero values
    var i int           // 0
    var f float64       // 0.0
    var s string        // ""
    var b bool          // false
    var p *int          // nil

    fmt.Println(i, f, s, b, p)
    // Output: 0 0.0  false <nil>
}

Type Conversion

package main

import (
    "fmt"
    "strconv"
)

func main() {
    // Explicit type conversion
    var i int = 42
    var f float64 = float64(i)
    var s string = fmt.Sprintf("%d", i)

    fmt.Println(f, s)

    // String conversions
    str := "123"
    num, err := strconv.Atoi(str)      // string to int
    if err != nil {
        fmt.Println("Error:", err)
    }

    str2 := strconv.Itoa(num)          // int to string
    fmt.Println(num, str2)

    // Float conversions
    f64, _ := strconv.ParseFloat("3.14", 64)
    fmt.Println(f64)
}

Constants

package main

import "fmt"

func main() {
    // Constant declaration
    const Pi = 3.14159
    const Greeting = "Hello, Go!"
    const MaxInt = 9223372036854775807

    // Typed constants
    const TypedInt int = 42
    const TypedFloat float64 = 3.14

    // Multiple constants
    const (
        Red = 0
        Green = 1
        Blue = 2
    )

    fmt.Println(Pi, Greeting, Red)
}

Iota for Enumerations

package main

import "fmt"

func main() {
    // Iota generates incrementing values
    const (
        Sunday = iota    // 0
        Monday           // 1
        Tuesday          // 2
        Wednesday        // 3
        Thursday         // 4
        Friday           // 5
        Saturday         // 6
    )

    // Iota with expressions
    const (
        Byte = 1 << (10 * iota)
        Kilobyte
        Megabyte
        Gigabyte
    )

    fmt.Println(Sunday, Monday, Kilobyte, Megabyte)
}

Best Practices

โœ… Good: Clear Variable Names

// DO: Use descriptive names
var userName string = "alice"
var userAge int = 30
var isActive bool = true

โŒ Bad: Unclear Variable Names

// DON'T: Use single letters or unclear names
var u string = "alice"
var a int = 30
var x bool = true

โœ… Good: Use Type Inference

// DO: Let compiler infer types when obvious
name := "Bob"
age := 25
price := 19.99

โŒ Bad: Unnecessary Type Specification

// DON'T: Specify type when it's obvious
var name string = "Bob"
var age int = 25

โœ… Good: Use Constants for Fixed Values

// DO: Use constants for values that don't change
const MaxRetries = 3
const DefaultTimeout = 30 * time.Second

โŒ Bad: Magic Numbers

// DON'T: Use magic numbers in code
if retries > 3 {
    // ...
}

Summary

Go’s type system provides:

  1. Strong typing with type safety
  2. Type inference for cleaner code
  3. Zero values for safe defaults
  4. Type conversion when needed
  5. Constants for immutable values
  6. Iota for enumerations

Understanding these fundamentals is crucial for writing idiomatic Go code.

Comments