Formatted IO

Back

Loading concept...

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?
Print 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 = Speaking
  • Scan, Scanln, Scanf = Listening
  • %s, %d, %f, %v = Secret Codes

Go forth and make your programs talk! 🎉

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.