Skip to content

Take a Formatted User Input in Golang (Extract Data)

Oh we know the input format and we want to extract data from some exact position of that, Scanf from fmt package will help us:

func Scanf(format string, a ...any) (n int, err error)

Take a look at this example which helps us to extract data from an user input:

package main

import (
	"fmt"
	"log"
)

func main() {
	var firstName string
	var department string
	var Age int

	fmt.Println("input the text:")

	_, err := fmt.Scanf("%s is %d from %s", &firstName, &Age, &department)

	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("firstName", firstName)
	fmt.Println("department", department)
	fmt.Println("Age", Age)
}

When it asks for input enter this line:

Morteza is 23 from design

Or

Morteza is 23 from design and any text after it will match

Leave a Reply

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