2.2 Golang Basic Data Types: int, float, bool, string
TL;DR
- Data types are labels that tell the computer what kind of information you're storing (e.g., a number, text, or a true/false value).
- Use
intfor whole numbers, like5or-100. - Use
float64for decimal numbers, like3.14or99.99. - Use
boolfor simple true or false answers. - Use
stringfor any kind of text, like"Hello, world!".
Why This Matters
Imagine trying to build a house with unlabeled materials. You might grab a glass pane thinking it's a wooden plank—and that would end badly! In programming, data types are those labels. They tell Go (the programming language) exactly what kind of data it's holding.
Getting types right is the very first step to writing clear, predictable, and bug-free code. It helps the computer work efficiently and prevents you from, say, trying to do math with a sentence. Learning these four basic types is like learning the alphabet before you write your first story.
Concepts in Plain English
Think of variables as storage boxes. A data type is the label on the box that tells you what you're allowed to put inside.
- Integer (
int): This is a box for whole apples only. You can put 1, 5, or 100 apples in it, but not half an apple. - Float (
float64): This is a measuring cup for liquids. It can hold 1.5 liters, 0.25 liters, or exactly 2 liters. It's for anything with a decimal point. - Boolean (
bool): This is a light switch. It can only beon(true) oroff(false). There's no in-between. - String (
string): This is a label maker. It prints out text—a single letter, a word, or a whole sentence.
Here's a quick cheat sheet:
| Term | Simple Definition | Where It Shows Up |
| Variable | A named container for storing data. | myVariable := "some data" |
Integer (int) | A data type for whole numbers (no decimals). | var userCount int = 50 |
Float (float64) | A data type for numbers with decimals. | var price float64 = 19.95 |
Boolean (bool) | A data type for true or false values. | var isActive bool = true |
String (string) | A data type for text. | var message string = "Welcome!" |
Quick Setup
You don't need to install anything to try these examples! We'll use the Go Playground, a free online tool for running Go code right in your browser.
- Open your web browser and go to https://go.dev/play/.
- You'll see a simple text editor with some code already in it.
- Just delete the existing code and paste in the examples from this post.
- Click the "Run" button to see the output. Easy!
Do It Step by Step
Let's see how to declare and use each of these types in Go.
1. Storing Whole Numbers with int
The goal here is to create a variable that can only hold whole numbers.
Print it to see the result. The fmt.Println() function prints things to the screen.
package main
import "fmt"
func main() {
var userAge int
userAge = 35
// WHY: We're printing the contents of our variable to see what's inside.
fmt.Println(userAge)
}
Assign a value to it. Use the = sign to put a number into your variable.
// Continuing from above...
userAge = 35 // Put the number 35 into our 'userAge' box.
Declare an integer variable. We use the keyword var followed by the variable name and then its type, int.
package main
import "fmt"
func main() {
// WHY: We're creating a 'box' named 'userAge' that can only hold integers.
var userAge int
}
- Input → Output:
- Code:
fmt.Println(userAge) - What you should see:
35
- Code:
Pro tip — You can declare and assign in one line using:=. Go automatically figures out the type for you!userAge := 35does the same thing as the code above but is much shorter.
2. Storing Decimal Numbers with float64
The goal is to store numbers that have a fractional part, like prices or measurements.
Print it out.
package main
import "fmt"
func main() {
var productPrice float64 = 129.99
// WHY: Print the price to check if it was stored correctly.
fmt.Println("The price is:", productPrice)
}
Declare a float variable. This time, we label the type as float64.
package main
import "fmt"
func main() {
// WHY: We need a variable that can handle decimals for something like a price.
var productPrice float64 = 129.99
}
- Input → Output:
- Code:
fmt.Println("The price is:", productPrice) - What you should see:
The price is: 129.99
- Code:
3. Storing True/False with bool
The goal is to keep track of a state that can only be one of two things, like "on" or "off."
Print it to see its state.
package main
import "fmt"
func main() {
var isFeatureEnabled bool = true
// WHY: We print the variable to confirm the feature's status.
fmt.Println("Is the new feature on?", isFeatureEnabled)
}
Declare a boolean variable. The type is bool, and the only valid values are true and false.
package main
import "fmt"
func main() {
// WHY: We want to track if a feature is enabled or not. A boolean is perfect for this.
var isFeatureEnabled bool = true
}
- Input → Output:
- Code:
fmt.Println("Is the new feature on?", isFeatureEnabled) - What you should see:
Is the new feature on? true
- Code:
4. Storing Text with string
The goal is to hold text, from a single character to an entire paragraph.
Print the greeting.
package main
import "fmt"
func main() {
var userName string = "Alex"
// WHY: We combine some text with our variable to create a personalized message.
fmt.Println("Hello,", userName)
}
Declare a string variable. The type is string, and the value must be enclosed in double quotes " ".
package main
import "fmt"
func main() {
// WHY: We're creating a variable to hold a user's name, which is text.
var userName string = "Alex"
}
- Input → Output:
- Code:
fmt.Println("Hello,", userName) - What you should see:
Hello, Alex
- Code:
Here is a summary table to help you choose the right type:
| Type Name | What It Holds | Example Value | When to Use It |
int | Whole numbers | 42, -10 | Counting items, user IDs, ages |
float64 | Decimal numbers | 3.14, 0.05 | Prices, scientific measurements, percentages |
bool | True or false | true, false | Tracking settings, login status, conditions |
string | Text | "Hello", "🚀" | Usernames, messages, file paths |
Examples Section
Let's put it all together.
Example A: The Basic Profile
This is a minimal example that declares one of each basic type to represent a user profile. Copy and paste this into the Go Playground and click "Run".
package main
import "fmt"
func main() {
// A person's name is text.
var name string = "Camila"
// Age is a whole number.
var age int = 28
// A rating could have decimals.
var satisfactionScore float64 = 4.8
// Whether they are a paying customer is a simple yes/no.
var isPremiumUser bool = true
// Print everything out!
fmt.Println("User Profile:")
fmt.Println("Name:", name)
fmt.Println("Age:", age)
fmt.Println("Score:", satisfactionScore)
fmt.Println("Premium:", isPremiumUser)
}
Example B: Simple Shopping Cart Calculation
This shows how different types can interact. We'll calculate the total cost of buying a few items.
package main
import "fmt"
func main() {
// The item name is text.
var itemName string = "Coffee Mug"
// The price has decimals.
var pricePerItem float64 = 12.50
// How many we want to buy is a whole number.
var quantity int = 3
// WHY: To calculate the total, we must convert the integer `quantity`
// to a float64 so it can be multiplied with `pricePerItem`.
// You can't multiply an int and a float directly!
var totalCost float64 = pricePerItem * float64(quantity)
fmt.Println("Item:", itemName)
fmt.Println("Total Cost:", totalCost)
}
How to Choose a Data Type
Here’s a simple flowchart to help you decide which type to use.
flowchart LR
A[Start: I have some data] --> B{What kind of data is it?};
B --> C{Is it a whole number?};
C -- Yes --> D[Use int];
C -- No --> E{Does it have a decimal?};
E -- Yes --> F[Use float64];
E -- No --> G{Is it just true or false?};
G -- Yes --> H[Use bool];
G -- No --> I{Is it text?};
I -- Yes --> J[Use string];
An ASCII diagram showing the decision process: Start with your data, then ask if it's a whole number (int), a decimal (float64), a true/false value (bool), or text (string).
Common Pitfalls
- Putting a decimal in an
int. Anintcan only hold whole numbers.var myNumber int = 99.0← This will cause an error!
- Forgetting quotes for
strings. Text must always be wrapped in double quotes.var myText string = Hello← This won't work. It should be"Hello".
- Mixing number types. You cannot add an
intto afloat64directly without converting one of them first (like we did in Example B). Go is very strict about this to prevent mistakes.
FAQ
- What's the difference between int and float64 again?int is for whole numbers only (like 1, 2, 3...). float64 is for numbers that need a decimal point (like 1.5, 2.75, 3.0).
- Can I change a variable's type later?No. In Go, once you declare a variable as a certain type (e.g., int), it stays that type forever. This is a feature called "static typing," and it helps catch bugs early.
- Why do you keep mentioning UTF-8 for strings?It just means that Go strings are built to handle modern text from any language in the world, including emojis like 🚀 or characters like 你好, without any extra work from you. It's a great built-in feature.
- Do I always have to type var name string = "Alex"? It feels long.Nope! You can use the := shorthand like this: name := "Alex". Go will automatically detect that "Alex" is a string and assign the correct type. Most Go developers use this shorter version when possible.
Recap
You've just learned the fundamental building blocks of data in Go. Nicely done!
- Every piece of data in Go has a type, which tells the computer what it is.
- The four basic types are
int(whole numbers),float64(decimals),bool(true/false), andstring(text). - Choosing the right type is essential for writing code that works correctly.
- You can experiment with all these types in the Go Playground without any setup.
- Next up: You can start learning about operators to perform actions with these types, like adding numbers or joining strings together.