Variables, Constants, and Data Types
# 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
varkeyword.
-
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.
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.-
intdefaults to0
-
float64defaults to0.0
-
stringdefaults to""(empty string)
-
booldefaults tofalse
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.
*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. 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.
- 2. Floating-Point (Decimals):
-
float32: 32-bit decimal.
-
float64: 64-bit decimal. (The standard default in Go).
- 3. Strings (Text):
-
string: A sequence of UTF-8 characters enclosed in double quotes"Hello".
- 4. Booleans (True/False):
-
bool: Can only betrueorfalse.
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 theconst keyword. You cannot use := with constants.
8. Multiple Variable Declaration
You can declare multiple variables cleanly in a block to save space.Or on a single line:
9. Common Mistakes
-
Unused Variables: Just like unused imports, if you declare
city := "New York"and never usecityin your code, Go will throw a compile-time error. Go hates dead code!
-
Using
:=to update:age := 20creates the variable. If you writeage := 21on the next line, it causes an error becauseagealready exists. Useage = 21to update.
10. Best Practices
-
Use
:=almost everywhere: It makes code cleaner and more readable. Only usevarwhen 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, notuseraccountbalance).
11. Exercises
-
1.
Create a short-declared variable
temperatureand set it to 98.6.
-
2.
Create a constant
companyNameand set it to "TechCorp".
-
3.
Print both variables using
fmt.Println. Try to update the constant and observe the compiler error.
12. MCQs with Answers & Explanations
Which keyword is used for explicit variable declaration?
What is the short variable declaration operator in Go?
:= 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.*
What is the default "zero value" for an uninitialized int in Go?
What is the default "zero value" for a bool?
Which keyword creates a variable that cannot be modified after creation?
What happens if you declare a variable but never use it in your code?
Go is a "Statically Typed" language. What does this mean?
Which data type is the standard default for decimals in Go?
How do you correctly update a variable that was previously declared using age := 20?
13. Interview Preparation
Interview Questions:- 1. What is type inference, and how does Go implement it?
- 2. Explain the concept of "Zero Values" in Go and why it is safer than C or C++.
- 3. Why does Go strictly throw errors for unused variables at compile-time?
Debugging Task: A junior developer writes:
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 achar 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 usevar 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.