🧾 1. Declaring Variables in Go
✅ A. Using var with type
var age int = 25
var name string = "Alice"
var isActive bool = true
Here, you're telling Go both the name of the variable and its type.
✅ B. Using var with type inference
var city = "New York"
var temperature = 29.5
Go infers the type based on the value, so you don’t need to write it explicitly.
✅ C. Short variable declaration (:=) — used inside functions
count := 100
greeting := "Hello"
This is the most common way to declare variables inside functions — short and clean.
📤 2. Printing Variables
In Go, fmt.Println and fmt.Printf are commonly used for output.
🔸 Print on different lines (automatically adds new lines):
fmt.Println("Name:", name)
fmt.Println("Age:", age)
Output:
Name: Alice
Age: 25
🔸 Print on the same line:
fmt.Print("Name: ", name, ", Age: ", age)
Output:
Name: Alice, Age: 25
🔸 Formatted output using fmt.Printf:
fmt.Printf("Name: %s, Age: %d, Temperature: %.2f\n", name, age, temperature)
Format specifiers:
- %s = string
- %d = integer
- %f = float (use %.2f for 2 decimal places)
- %t = boolean
- %v = any value
Output:
Name: Alice, Age: 25, Temperature: 29.50
🔍 3. Common Go Types
✅ 4. Constants
You can also declare constants that don’t change:
const Pi = 3.14159
🧾 5. fmt.Sprintf – Formatting Without Printing
Sprintf works just like Printf, but instead of printing to the screen, it returns the formatted string.
Think of it like preparing a string to use somewhere else, not just displaying it.
✅ Example:
name := "Alice"
age := 25
temperature := 29.5678
formatted := fmt.Sprintf("Name: %s, Age: %d, Temperature: %.1f", name, age, temperature)
fmt.Println(formatted)
What happens here:
- fmt.Sprintf creates a formatted string
- fmt.Println then prints that string
Output:
Name: Alice, Age: 25, Temperature: 29.6
📌 When to Use Sprintf?
Use it when:
- You want to store a formatted string in a variable
- You want to build messages for logging, errors, or UI
- You don’t want to print immediately
Bonus Example—Log Message:
log := fmt.Sprintf("[INFO] User %s (age %d) logged in", name, age)
fmt.Println(log)
Output:
[INFO] User Alice (age 25) logged in
Top comments (0)