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)