Skip to content

Go: How to Take Multiple User Inputs From One Line

You need to accept multiple inputs (with different types) from a user and all of them are in one line!

Scanln from the fmt package is your friend:

func Scanln(a ...any) (n int, err error)

Enjoy this simple example which reads two string and one integer from one line input:

package main

import (
	"fmt"
	"log"
)

func main() {
	var firstName, lastName string
	var age int

	fmt.Println("Enter you firstname, lastname and your age:")

	n, err := fmt.Scanln(&firstName, &lastName, &age)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("how many inputs read:", n)
	fmt.Println("firstName:", firstName)
	fmt.Println("lastName:", lastName)
	fmt.Println("age:", age)
}

And enter this input when it asks for the input:

Morteza Rostami 23

Leave a Reply

Your email address will not be published. Required fields are marked *