0
0
Goprogramming~5 mins

Basic input concepts in Go

Choose your learning style9 modes available
Introduction
We use input to let the user give information to the program. This helps the program do different things based on what the user wants.
When you want to ask the user for their name.
When you need the user to enter a number to calculate something.
When you want to get a choice from the user to decide what to do next.
When you want to read a line of text from the user.
When you want to get multiple pieces of information from the user.
Syntax
Go
package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	reader := bufio.NewReader(os.Stdin)
	input, _ := reader.ReadString('\n')
	fmt.Println("You typed:", input)
}
Use bufio.NewReader(os.Stdin) to read input from the keyboard.
The ReadString('\n') method reads until the user presses Enter.
Examples
This example uses fmt.Scanln to read a single word input from the user.
Go
package main

import (
	"fmt"
)

func main() {
	var name string
	fmt.Print("Enter your name: ")
	fmt.Scanln(&name)
	fmt.Println("Hello,", name)
}
This example reads a whole line of text including spaces using bufio.NewReader.
Go
package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	reader := bufio.NewReader(os.Stdin)
	fmt.Print("Enter a sentence: ")
	text, _ := reader.ReadString('\n')
	fmt.Println("You wrote:", text)
}
Sample Program
This program asks the user for their favorite color, reads the input line, removes the newline, and then prints a friendly message.
Go
package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

func main() {
	reader := bufio.NewReader(os.Stdin)
	fmt.Print("What is your favorite color? ")
	color, _ := reader.ReadString('\n')
	color = strings.TrimSpace(color) // remove newline
	fmt.Printf("Wow! %s is a nice color.\n", color)
}
OutputSuccess
Important Notes
Always handle the newline character when reading input lines to avoid extra spaces.
Use fmt.Scanln for simple inputs without spaces, and bufio.NewReader for full lines.
Input reading can return errors; in simple cases you can ignore them with _ but in real programs handle errors properly.
Summary
Input lets the program get information from the user.
Use fmt.Scanln for simple word inputs and bufio.NewReader for full lines.
Always clean input by removing extra spaces or newlines.