The Talking Computer: How Go Speaks and Listens
A Story About Communication
Imagine you have a magical messenger bird. This bird can:
- Speak messages to your friends (Formatted Output)
- Listen to what your friends say back (Formatted Input)
- Know special codes to describe things perfectly (Format Verbs)
In Go, the fmt package is your magical messenger bird! Letâs learn how to use it.
Chapter 1: Formatted Output - Teaching Your Computer to Talk
What is Formatted Output?
Think of it like this: You want to tell your mom about your day. You could say:
âSchool. Lunch. Play.â
Or you could say:
âI went to school, ate pizza for lunch, and played soccer!â
Formatted output lets your computer speak in complete, beautiful sentences!
The Three Magic Spells
Go gives you three main ways to print things:
1. fmt.Print() - The Shy Speaker
fmt.Print("Hello")
fmt.Print("World")
// Output: HelloWorld
It speaks but doesnât add space or new lines. Words stick together!
2. fmt.Println() - The Polite Speaker
fmt.Println("Hello")
fmt.Println("World")
// Output:
// Hello
// World
It speaks and goes to a new line after each message. Like pressing âEnterâ!
3. fmt.Printf() - The Smart Speaker
name := "Luna"
age := 8
fmt.Printf("My name is %s and I am %d years old", name, age)
// Output: My name is Luna and I am 8 years old
It uses special codes (format verbs) to put values in the right places!
Quick Comparison
| Function | Adds Space? | New Line? | Uses Codes? |
|---|---|---|---|
| No | No | No | |
| Println | Yes | Yes | No |
| Printf | No | No | Yes! |
Writing to Strings
Sometimes you donât want to speak out loud. You want to write a note!
message := fmt.Sprintf("Hello, %s!", "World")
// message now contains: "Hello, World!"
Sprintf is like Printf, but it saves the message instead of showing it.
Chapter 2: Formatted Input - Teaching Your Computer to Listen
What is Formatted Input?
Imagine asking your friend their favorite color. They say âBlue!â Now you need to remember that answer.
Formatted input lets your computer listen and remember what people type!
The Listening Spells
1. fmt.Scan() - The Simple Listener
var name string
fmt.Scan(&name)
// User types: Luna
// name now contains: "Luna"
The & symbol is like saying âPut the answer here!â It points to where to store the answer.
2. fmt.Scanln() - The Line Listener
var word1, word2 string
fmt.Scanln(&word1, &word2)
// User types: Hello World [Enter]
// word1 = "Hello", word2 = "World"
It listens until the user presses Enter!
3. fmt.Scanf() - The Pattern Listener
var day int
var month string
fmt.Scanf("%d %s", &day, &month)
// User types: 25 December
// day = 25, month = "December"
It listens for a specific pattern! Like a template for answers.
Why the & Symbol?
Think of & like an arrow pointing to a box:
&name â [___] â "Put the answer in this box!"
Without &, Go doesnât know WHERE to put the answer!
graph TD A["User Types Something"] --> B["fmt.Scan reads it"] B --> C["& points to a variable"] C --> D["Answer stored safely!"]
Chapter 3: Format Verbs - The Secret Codes
What are Format Verbs?
Format verbs are like secret codes that tell Go: âHere comes a number!â or âHere comes a word!â
They always start with % (percent sign).
The Most Important Codes
For Any Type: %v (The Universal Code)
fmt.Printf("Value: %v", 42) // Value: 42
fmt.Printf("Value: %v", "hello") // Value: hello
fmt.Printf("Value: %v", true) // Value: true
%v works with anything! Itâs the âfigure it out yourselfâ code.
For Strings: %s
name := "Luna"
fmt.Printf("Hello, %s!", name)
// Output: Hello, Luna!
For Integers: %d
age := 8
fmt.Printf("I am %d years old", age)
// Output: I am 8 years old
For Floats: %f
price := 3.99
fmt.Printf("Price: $%f", price)
// Output: Price: $3.990000
Want fewer decimals? Use %.2f:
fmt.Printf("Price: $%.2f", price)
// Output: Price: $3.99
For Booleans: %t
happy := true
fmt.Printf("Are you happy? %t", happy)
// Output: Are you happy? true
For Type Discovery: %T
fmt.Printf("Type: %T", 42) // Type: int
fmt.Printf("Type: %T", "hello") // Type: string
This tells you what kind of thing it is!
The Complete Format Verb Family
| Code | Meaning | Example |
|---|---|---|
%v |
Any value | 42, "hi", true |
%s |
String | "hello" |
%d |
Integer | 42 |
%f |
Float | 3.14 |
%t |
Boolean | true |
%T |
Type name | int, string |
%q |
Quoted string | "hello" |
%x |
Hex number | 2a (for 42) |
%b |
Binary | 101010 (for 42) |
%% |
Literal % | % |
Special Formatting Tricks
Adding Width (Padding)
fmt.Printf("|%10s|", "cat")
// Output: | cat|
The number 10 means âuse at least 10 spaces.â Adds padding on the left!
Left Align with -
fmt.Printf("|%-10s|", "cat")
// Output: |cat |
The minus sign pushes the text to the left!
Leading Zeros
fmt.Printf("%05d", 42)
// Output: 00042
Perfect for showing times like 09:05!
Chapter 4: Putting It All Together
A Real Example: A Simple Greeting Card
package main
import "fmt"
func main() {
var name string
var age int
fmt.Print("What is your name? ")
fmt.Scan(&name)
fmt.Print("How old are you? ")
fmt.Scan(&age)
fmt.Printf("\n--- GREETING CARD ---\n")
fmt.Printf("Dear %s,\n", name)
fmt.Printf("Happy %d birthday!\n", age)
fmt.Printf("---------------------\n")
}
Output:
What is your name? Luna
How old are you? 8
--- GREETING CARD ---
Dear Luna,
Happy 8 birthday!
---------------------
The Flow of Communication
graph TD A["Your Program"] -->|Printf/Print/Println| B["Screen Output"] C["User Typing"] -->|Scan/Scanln/Scanf| A A -->|Sprintf| D["Stored String"] E["Format Verbs"] -->|%s %d %f| A
Quick Reference: Choose Your Spell!
âI want to show somethingâŚâ
| Situation | Use This |
|---|---|
| Just show text | fmt.Print("text") |
| Show text + new line | fmt.Println("text") |
| Show with values mixed in | fmt.Printf("text %v", val) |
| Save to a string | fmt.Sprintf("text %v", val) |
âI want to read somethingâŚâ
| Situation | Use This |
|---|---|
| Read one word | fmt.Scan(&var) |
| Read until Enter | fmt.Scanln(&var) |
| Read specific pattern | fmt.Scanf("%d", &var) |
âWhich format verb do I use?â
| I have a⌠| Use |
|---|---|
| Text/String | %s |
| Whole number | %d |
| Decimal number | %f or %.2f |
| True/False | %t |
| Donât know/Any | %v |
You Did It!
Now you know how to make Go speak (output), listen (input), and use secret codes (format verbs) to communicate perfectly!
Remember:
Print,Println,Printf= SpeakingScan,Scanln,Scanf= Listening%s,%d,%f,%v= Secret Codes
Go forth and make your programs talk! đ
