Skip to main content
Go Language Fundamentals for Beginners to Advanced
CHAPTER 04 Beginner

Variables, Constants, and Data Types

Updated: May 17, 2026
5 min read

# CHAPTER 4

Variables, Constants, and Data Types

1. Introduction

To build useful applications, your program must store and manipulate data. Whether it's a user's name, an account balance, or a true/false flag indicating if a user is logged in, this data resides in the computer's memory. In Go, we use Variables to store data that can change, and Constants to store data that is fixed.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Declare variables using the var keyword.
  • Use the modern short variable declaration :=.
  • Understand Go's basic Data Types (int, float64, string, bool).
  • Declare immutable Constants.
  • Understand Static Typing and Type Inference.

3. Variables and Static Typing

Go is a Statically Typed language. This means once a variable is declared as an integer, it can NEVER hold a string. It is locked into its type. This prevents thousands of bugs that commonly plague languages like Python and JavaScript.

Method 1: Explicit Declaration (using var) You use the var keyword, followed by the name, then the type.

go
1234567891011
package main

import "fmt"

func main() {
    var age int = 25
    var name string = "Alice"
    var isVerified bool = true

    fmt.Println(name, "is", age, "years old. Verified:", isVerified)
}

4. Default Zero Values (Memory Behavior)

If you declare a variable but do not assign it a value, Go automatically assigns it a safe "Zero Value" instead of leaving unpredictable junk in memory.
  • int defaults to 0
  • float64 defaults to 0.0
  • string defaults to "" (empty string)
  • bool defaults to false
go
12
var score int
fmt.Println(score) // Prints: 0 (No "undefined" or "null" errors!)

5. Type Inference and the Short Declaration Operator :=

Typing var name string = "Alice" is too long. Since "Alice" is obviously a string, the Go compiler can infer the type automatically!

You can drop the var and the type, and use the Short Variable Declaration Operator :=. This is how 95% of variables are created in modern Go.

go
123456789101112
func main() {
    // Go infers that this is a string
    hero := "Batman" 
    
    // Go infers this is an int
    powerLevel := 9000 
    
    fmt.Println(hero, "has power", powerLevel)
    
    // To update a variable later, just use =, NOT :=
    powerLevel = 9001 
}

*Note: := can only be used INSIDE a function (like main). If you want to declare a global variable outside a function, you must use var.*

6. Core Data Types

Go provides highly optimized data types.
  1. 1. Integers (Whole numbers):
  • int: Standard integer. Automatically sizes to 32-bit or 64-bit depending on your OS.
  • uint: Unsigned integer (positive numbers only).
  • int8, int16, int32, int64: Specific memory sizes for optimization.
  1. 2. Floating-Point (Decimals):
  • float32: 32-bit decimal.
  • float64: 64-bit decimal. (The standard default in Go).
  1. 3. Strings (Text):
  • string: A sequence of UTF-8 characters enclosed in double quotes "Hello".
  1. 4. Booleans (True/False):
  • bool: Can only be true or false.

7. Constants

Sometimes you have data that should NEVER change while the program runs, like the value of Pi or a database URL. You use the const keyword. You cannot use := with constants.
go
12345678
func main() {
    const pi = 3.14159
    const appName = "My Backend App"
    
    // pi = 4.0 // ERROR! Cannot assign to a constant
    
    fmt.Println(appName, "uses Pi as", pi)
}

8. Multiple Variable Declaration

You can declare multiple variables cleanly in a block to save space.
go
12345
var (
    serverIP   = "192.168.1.1"
    serverPort = 8080
    isRunning  = true
)

Or on a single line:

go
1
x, y, z := 1, 2, 3

9. Common Mistakes

  • Unused Variables: Just like unused imports, if you declare city := "New York" and never use city in your code, Go will throw a compile-time error. Go hates dead code!
  • Using := to update: age := 20 creates the variable. If you write age := 21 on the next line, it causes an error because age already exists. Use age = 21 to update.

10. Best Practices

  • Use := almost everywhere: It makes code cleaner and more readable. Only use var when you need to declare a variable without immediately assigning it a value.
  • camelCase Naming: Variable names should start with a lowercase letter and capitalize subsequent words (e.g., userAccountBalance, not useraccountbalance).

11. Exercises

  1. 1. Create a short-declared variable temperature and set it to 98.6.
  1. 2. Create a constant companyName and set it to "TechCorp".
  1. 3. Print both variables using fmt.Println. Try to update the constant and observe the compiler error.

12. MCQs with Answers & Explanations

Question 1

Which keyword is used for explicit variable declaration?

Question 2

What is the short variable declaration operator in Go?

Q3. Can you use := outside of a function (in the global scope)? a) Yes b) No Answer: b) No. *Explanation: Outside of functions, every statement must begin with a keyword like var, func, or const.*
Question 4

What is the default "zero value" for an uninitialized int in Go?

Question 5

What is the default "zero value" for a bool?

Question 6

Which keyword creates a variable that cannot be modified after creation?

Question 7

What happens if you declare a variable but never use it in your code?

Question 8

Go is a "Statically Typed" language. What does this mean?

Question 9

Which data type is the standard default for decimals in Go?

Question 10

How do you correctly update a variable that was previously declared using age := 20?

13. Interview Preparation

Interview Questions:
  1. 1. What is type inference, and how does Go implement it?
  1. 2. Explain the concept of "Zero Values" in Go and why it is safer than C or C++.
  1. 3. Why does Go strictly throw errors for unused variables at compile-time?

Debugging Task: A junior developer writes:

go
12
name := "John"
name := "Doe"

Why does this fail? *Answer: You cannot redeclare a variable using := in the same scope. The second line should use =.*

14. FAQs

Q: Does Go have a char type? A: No, Go uses rune to represent single characters, which actually stores the 32-bit Unicode value of the character. We will cover this in Chapter 12.

Q: Can a variable's type change dynamically like in Python? A: Absolutely not. In Go, an int is forever an int. If you need a variable to hold anything, you use an interface{} (covered later), but strong typing is highly preferred.

15. Summary

Data storage in Go is safe and efficient. We use var for explicit declarations and := for quick, type-inferred declarations inside functions. Go's strict rules—like Static Typing, Default Zero Values, and throwing errors for unused variables—force developers to write bug-free, clean code. Constants (const) protect critical data from accidental modification.

16. Next Chapter Recommendation

Now that we have variables holding numbers and text, we need to do math and logic with them. In Chapter 5: Operators in Go, we will learn how to add, multiply, and compare data.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·