DEV Community

Huseyn
Huseyn

Posted on

Go variables, types, their declarations, and printing styles

🧾 1. Declaring Variables in Go

✅ A. Using var with type

var age int = 25
var name string = "Alice"
var isActive bool = true
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output:

Name: Alice
Age: 25
Enter fullscreen mode Exit fullscreen mode

🔸 Print on the same line:

fmt.Print("Name: ", name, ", Age: ", age)
Enter fullscreen mode Exit fullscreen mode

Output:

Name: Alice, Age: 25
Enter fullscreen mode Exit fullscreen mode

🔸 Formatted output using fmt.Printf:

fmt.Printf("Name: %s, Age: %d, Temperature: %.2f\n", name, age, temperature)
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

🔍 3. Common Go Types

common-go-type

✅ 4. Constants

You can also declare constants that don’t change:

const Pi = 3.14159
Enter fullscreen mode Exit fullscreen mode

🧾 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)
Enter fullscreen mode Exit fullscreen mode

What happens here:

  • fmt.Sprintf creates a formatted string
  • fmt.Println then prints that string

Output:

Name: Alice, Age: 25, Temperature: 29.6
Enter fullscreen mode Exit fullscreen mode

📌 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)
Enter fullscreen mode Exit fullscreen mode

Output:

[INFO] User Alice (age 25) logged in
Enter fullscreen mode Exit fullscreen mode

Top comments (0)