Input and Output in Golang (Making Your Code Talk!)

Go (or Golang, if you're feeling formal) allows you to interact with users by taking input and displaying output. Think of it like having a conversation with your computer—except it only listens to what you type and doesn’t judge your life choices (yet!).

Printing Output (Making Go Speak!)

Before we take input, let’s first learn how to make Go say something using fmt.Println:

package main
import "fmt"

func main() {
    fmt.Println("Hello, Go World!")
}

This will display:

Hello, Go World!

Yes, it’s simple, but every great program starts with a humble Hello, World!.

Taking User Input (Go Listens!)

Go lets you take input using fmt.Scan, fmt.Scanln, and fmt.Scanf. Let’s break it down.

fmt.Scanln - Basic Input

package main
import "fmt"

func main() {
    var name string
    fmt.Print("Enter your name: ")
    fmt.Scanln(&name)
    fmt.Println("Hello,", name, "! Welcome to Go!")
}

How it works:

  • fmt.Print prints without a newline (so your input stays on the same line).
  • fmt.Scanln(&name) waits for user input and stores it in name.
  • fmt.Println prints the greeting.

Example output:

Enter your name: Alice
Hello, Alice! Welcome to Go!

fmt.Scan - Taking Multiple Inputs

fmt.Scan is great when you need multiple values:

package main
import "fmt"

func main() {
    var age int
    var city string
    fmt.Print("Enter your age and city: ")
    fmt.Scan(&age, &city)
    fmt.Println("You are", age, "years old and live in", city, ".")
}

Example:

Enter your age and city: 25 Jakarta
You are 25 years old and live in Jakarta.

fmt.Scanf - Formatted Input (Fancy!)

Need more control? Use fmt.Scanf:

package main
import "fmt"

func main() {
    var name string
    var age int
    fmt.Print("Enter your name and age: ")
    fmt.Scanf("%s %d", &name, &age)
    fmt.Printf("Hello, %s! You are %d years old.\n", name, age)
}

Here, "%s %d" expects a string (name) and an integer (age).

Final Thoughts

Handling input and output in Go is easy once you get the hang of it. Now, go ahead and make your programs talk and listen—just don’t expect them to reply with deep philosophical answers. 

Post a Comment

0 Comments