0
0
Goprogramming~10 mins

Basic input concepts in Go - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Basic input concepts
Start program
Prompt user for input
Wait for user to type
User presses Enter
Read input into variable
Use input in program
End program
The program starts, asks the user for input, waits for the user to type and press Enter, then reads and stores the input for use.
Execution Sample
Go
package main
import "fmt"
func main() {
  var name string
  fmt.Print("Enter your name: ")
  fmt.Scanln(&name)
  fmt.Println("Hello,", name)
}
This program asks the user to enter their name, reads it, and then greets them.
Execution Table
StepActionInput/ConditionVariable StateOutput
1Program starts-name = ""-
2Print prompt-name = ""Enter your name:
3Wait for user inputUser types 'Alice' and presses Entername = ""-
4Read input into variable-name = "Alice"-
5Print greeting-name = "Alice"Hello, Alice
6Program ends-name = "Alice"-
💡 Program ends after printing greeting.
Variable Tracker
VariableStartAfter Step 4Final
name"""Alice""Alice"
Key Moments - 2 Insights
Why do we use &name in fmt.Scanln(&name)?
We use &name to pass the memory address of the variable so fmt.Scanln can store the input directly into it, as shown in step 4 of the execution_table.
What happens if the user just presses Enter without typing anything?
The variable 'name' will remain an empty string "", because fmt.Scanln reads what the user typed before Enter, as seen in step 3 and 4.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'name' after step 4?
A""
B"Alice"
Cnil
D"Enter your name:"
💡 Hint
Check the 'Variable State' column at step 4 in the execution_table.
At which step does the program print the greeting message?
AStep 5
BStep 4
CStep 2
DStep 6
💡 Hint
Look at the 'Output' column in the execution_table for the greeting message.
If the user inputs 'Bob' instead of 'Alice', which part of the execution_table changes?
AStep 5 output
BStep 2 output
CStep 3 and Step 4 variable state
DStep 1 action
💡 Hint
User input affects the variable state during reading input, see steps 3 and 4.
Concept Snapshot
Basic input in Go:
- Use fmt.Print to show prompt
- Use fmt.Scanln(&var) to read input
- &var passes variable address
- Input stored in variable for use
- Program continues after input
Full Transcript
This Go program starts by declaring a string variable 'name'. It prints a prompt asking the user to enter their name. The program then waits for the user to type and press Enter. Using fmt.Scanln with &name, it reads the input and stores it in the variable 'name'. Finally, it prints a greeting message including the entered name and ends. The key is passing the variable's address to read input correctly.