go-tutorial

Go Take Input

In this tutorial, you will learn to take input from the user in Go programming with the help of examples.

In Go, we use the scan() function to take input from the user. For example,

package main import "fmt"
func main() {
var name string
// takes input value for name
 fmt.Print("Enter your name: ")
fmt.Scan(&name)
fmt.Printf("Name: %s", name)
}

Output

Enter your name: Rosie
Name: Rosie

In the above example, the line

fmt.Scan(&name)

takes input value from the user and assigns it to the name variable.

Go programming provides three different variations of the Scan() method:

  • fmt.Scan()
  • fmt.Scanln()

Note that all of these functions are part of the fmt package. Before we can utilise these functions, we must first import the fmt package.

Go fmt.Scan()

As mentioned earlier, the Scan() function takes input from the user. However, it can only take input values up to a space

When it encounters a space, the value before space is assigned to the specified variable. For example,

package main 
import "fmt"
func main() {
var language string
// takes input value for name
fmt.Print("Enter your favorite language: ") 
fmt.Scan(&language) 
fmt.Printf("Favorite Language: %s", language)
}

Output

Enter your favorite language: Go Programming
Favorite Language: Go

In the above example, we have provided the input value Go Programming. However, we are only getting Go as the output.

This is because the Scan() function only takes input value up to the space.

Go fmt.Scanln()

We use the Scanln() function to get input values up to the new line. When it encounters a new

line, it stops taking input values. For example,

package main
import "fmt"
func main() { 
var name string 
var age int
// take name and age input 
fmt.Println("Enter your name and age:") 
fmt.Scanln(&name, &age) 
fmt.Printf("Name: %s\nAge: %d", name, age)
}

Output

Enter your name and age:
Maria
Name: Maria
Age: 0

In the above example, we have used the Scanln() function to take two input values for name and age.

fmt.Scanln(&name, &age)

However, when we press enter after providing the first value, Maria, the program exits. This is because Scanln() only takes input value up to the new line, so when it encounters the enter after Maria, it stops taking input.

If we want to take input values for age, we must provide values separated by space.

Enter your name and age:
Maria 27
Name: Maria
Age: 27

Here, we have separated two inputs by space, so Scanln() can take both input values.

RECOMMENDED ARTICLES





Leave a Reply

Your email address will not be published.