Golang Backend Real-World (Part 3): Variables, Types & Constants

Golang Backend Real-World (Part 3): Variables, Types & Constants
Golang Backend Real-World (Part 3): Variables, Types & Constants

In this part of the Golang Backend Real-World series, we explore the foundational concepts that power every Go backend application: variables, data types, and constants.
Whether you’re building REST APIs, microservices, or CLI tools, these concepts appear everywhere in real-world Golang code.

1. Variables in Go

Variables store values that can change throughout the lifecycle of a program. Go is statically typed, meaning each variable has a specific type determined at compile time.

1.1 Declaring variables using var

var name string = "Leaf"
var age int = 30

This is the most explicit form of variable declaration in Go.

1.2 Declaring variables without initialization (zero values)

Go assigns a zero value when no initial value is provided:

var message string  // ""
var count int       // 0
var active bool     // false

This prevents undefined or null-type issues.


1.3 Short declaration (:=)

Commonly used inside functions for cleaner code:

title := "Golang Tutorial"
views := 102
enabled := true

Go infers the type automatically.


1.4 Declaring multiple variables

var a, b, c = 1, 2, 3

Or in block format:

var (
    username = "admin"
    attempts = 3
    isAdmin  = false
)

This is useful for grouping related variables.


2. Data Types in Go

Go provides a powerful type system optimized for both performance and readability. Here are the types most relevant to backend systems.


2.1 Numeric types

  • int, int8, int16, int32, int64
  • uint versions for unsigned integers
  • float32, float64 for decimal numbers

Example:

price := 19.99
quantity := 5


2.2 Strings

Go’s strings are UTF-8 encoded:

message := "Hello, Go!"


2.3 Boolean

isValid := true


2.4 Composite Types (important for backend systems)

Slice

roles := []string{"admin", "user"}

Map

config := map[string]string{
    "env": "production",
    "region": "ap-southeast-1",
}

Struct — core building block of backend models

type User struct {
    Name string
    Age  int
}


3. Constants in Go

Constants represent values that never change.

const AppName = "Codevivu.com"
const MaxConnections = 10


3.1 Using iota for enumerations

iota is a counter that increments automatically:

const (
    StatusPending = iota     // 0
    StatusApproved           // 1
    StatusRejected           // 2
)

This is useful for defining business logic states.


4. Summary

In Part 3, you learned:

  • Different ways to declare variables in Go
  • How zero values work
  • Core primitive and composite data types
  • How to define constants and enumerations using iota
  • Practical examples used in real backend systems

About Leaf 49 Articles
"Thành công nuôi dưỡng sự hoàn hảo. Sự hoàn hảo lại nuôi lớn thất bại. Chỉ có trí tưởng tượng mới tồn tại."