Skip to content

Go Data Types

Go is statically typed, meaning every variable has a specific type determined at compile time.

1. Variables

There are two main ways to declare variables:

package main
import "fmt"

func main() {
    // 1. Full declaration (var name type = value)
    var name string = "Alice"

    // 2. Short declaration (name := value)
    // Type is inferred automatically. Only works inside functions.
    age := 25

    fmt.Println(name, age)
}

2. Basic Types

  • Integers: int, int8, int64, uint (unsigned). Usually, just use int.
  • Floats: float32, float64. Usually, just use float64.
  • Booleans: bool (true or false).
  • Strings: string (UTF-8 encoded).

3. Zero Values

Variables declared without an explicit initial value are given their zero value: - 0 for numeric types. - false for booleans. - "" (empty string) for strings.

4. Constants

Constants are values that cannot be changed once declared.

const Pi = 3.14
const StatusOK = 200

5. Type Conversions

Go never performs implicit conversions (e.g., you can't add an int to a float64). You must be explicit.

1
2
3
var i int = 42
var f float64 = float64(i) // Correct
// var f float64 = i        // Error!

6. Strings and Immutability

Strings in Go are immutable. You cannot change a single character in a string. Instead, you create a new string.

1
2
3
s := "hello"
// s[0] = 'H' // Error!
s = "H" + s[1:] // Correct: creates a new string