GoLang - Take Input

2 minute read

In this tutorial, you will learn about how to take input in Go Programming with the help of example.

In Go programming, taking user input is a fundamental skill that allows your programs to interact with users and create dynamic experiences. Whether you want to ask for a name, get a number, or receive any other type of input, Go provides simple and effective methods to accomplish this. In this tutorial, we will explore the different ways to take user input in Go programming, using clear and easy-to-understand language. So let’s get started!

Method 1: Using the fmt Package and Scanln Function

  1. Start by importing the 'fmt' package at the beginning of your Go program:
    import "fmt"
    
  2. Declare a variable to store the user’s input. For example, if you want to ask for the user’s name, you can use a string variable:
    var name string
    
  3. Print a prompt message to ask the user for input:
    fmt.Println("What is your name?")
    
  4. Use the 'Scanln' function from the 'fmt' package to read the user’s input and store it in the variable you declared earlier:
    fmt.Scanln(&name)
    
  5. Finally, you can use the input in your program. For example, let’s print a personalized greeting message:
    fmt.Println("Hello,", name, "!")
    

Method 2: Using the fmt Package and Scan Function

  1. Follow the first two steps from Method 1 to import the 'fmt' package and declare a variable to store the input.

  2. Print a prompt message to ask the user for input:
    fmt.Println("How old are you?")
    
  3. Use the 'Scan' function instead of 'Scanln' to read a single value from the user:
    fmt.Scan(&age)
    
  4. Utilize the input in your program. For instance, let’s print a message displaying the entered age:
    fmt.Println("You are", age, "years old.")
    

Method 3: Taking Multiple Inputs

  1. Begin by importing the 'fmt' package and declaring the variables you need to store multiple inputs.

  2. Print a prompt message for the first input:
    fmt.Println("What is your name?")
    
  3. Use the 'Scanln' function to read the user’s input and store it in the corresponding variable:
    fmt.Scanln(&name)
    
  4. Repeat steps 2 and 3 for each additional input you want to take.

  5. Utilize the entered values in your program as needed.

Conclusion

Taking user input in Go programming allows your programs to interact with users and create dynamic experiences. By utilizing the Scanln and Scan functions from the fmt package, you can easily incorporate user input into your Go programs. In this tutorial, we explored three methods to take user input in Go, from a single input to multiple inputs. By following these step-by-step instructions, you now have the knowledge to create programs that respond to user input. So go ahead, start experimenting, and enhance your Go programs with user interaction!

Updated: