Home »
Golang »
Golang Reference
Golang fmt.Fscan() Function with Examples
Golang | fmt.Fscan() Function: Here, we are going to learn about the Fscan() function of the fmt package with its usages, syntax, and examples.
Submitted by IncludeHelp, on October 08, 2021
fmt.Fscan()
In Go language, the fmt package implements formatted I/O with functions analogous to C's printf() and scanf(). The Fscan() function is an inbuilt function of the fmt package which is used to scan the text read from r (io.Reader), and stores the successive space-separated values into the given successive arguments. The newlines count as space.
It accepts two parameters (r io.Reader, a ...interface{}) and returns the number of total items successfully scanned and an error if occurred during the read operation.
Syntax:
func Fscan(r io.Reader, a ...interface{}) (n int, err error)
Parameter(s):
- r : The standard Input/Output.
- a : A custom type that is used to specify a set of one or more method signatures, here we can provide a set of the variables, constants, functions, etc.
Return Value:
The return type of the fmt.Fscan() function is (n int, err error), it returns the number of total items successfully scanned and an error if occurred during the read operation.
Example 1:
// Golang program to demonstrate the
// example of fmt.Fscan() function
package main
import (
"fmt"
"strings"
)
func main() {
var name string
var age int
// Function Fscan() returns,
// n: Number of items successfully scanned
// err: Error if any
n, err := fmt.Fscan(strings.NewReader("Alexander 47"),
&name, &age)
// Printing variables, items scanned, err
fmt.Println("Name :", name)
fmt.Println("Age :", age)
fmt.Println(n, "Items successfully scanned")
fmt.Println("Error", err)
}
Output:
Name : Alexander
Age : 47
2 Items successfully scanned
Error <nil>
Example 2:
// Golang program to demonstrate the
// example of fmt.Fscan() function
package main
import (
"fmt"
"strings"
)
func main() {
var (
name string
roll int
age int
perc float32
)
// Function Fscan() returns,
// n: Number of items successfully scanned
// err: Error if any
n, err := fmt.Fscan(strings.NewReader("Alvin 101 47 87.50"),
&name, &roll, &age, &perc)
// Printing variables, items scanned, err
fmt.Println("Name :", name)
fmt.Println("Roll :", roll)
fmt.Println("Age :", age)
fmt.Println("Percentage :", perc)
fmt.Println(n, "Items successfully scanned")
fmt.Println("Error", err)
}
Output:
Name : Alvin
Roll : 101
Age : 47
Percentage : 87.5
4 Items successfully scanned
Error <nil>
Golang fmt Package »