×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang fmt.Scan() Function with Examples

Golang | fmt.Scan() Function: Here, we are going to learn about the Scan() function of the fmt package with its usages, syntax, and examples.
Submitted by IncludeHelp, on October 09, 2021

fmt.Scan()

In Go language, the fmt package implements formatted I/O with functions analogous to C's printf() and scanf(). The Scan() function is an inbuilt function of the fmt package which is used to scan text read from standard input, storing successive space-separated values into successive arguments. Newlines count as space.

It accepts one parameter (a ...interface{}) and returns the number of total items successfully scanned and an error if occurred during the read operation.

Syntax:

func Scan(a ...interface{}) (n int, err error)

Parameter(s):

  • 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.Scan() 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.Scan() function

package main

import (
	"fmt"
)

func main() {
	var number int

	// Input a number
	fmt.Print("Input a number: ")
	n, err := fmt.Scan(&number)

	// Print the value, n and err
	fmt.Println("number: ", number)
	fmt.Println(n, " Item(s) scanned.")
	fmt.Println("Error: ", err)
}

Output:

RUN 1:
Input a number: 108
number:  108
1  Item(s) scanned.
Error:  <nil>

RUN 2:
Input a number: Hello
number:  0
0  Item(s) scanned.
Error:  expected integer

Example 2:

// Golang program to demonstrate the
// example of fmt.Scan() function

package main

import (
	"fmt"
)

func main() {
	var name string
	var age int

	// Input name from the user
	fmt.Print("Enter name: ")
	fmt.Scan(&name)

	// Input name from the user
	fmt.Print("Enter age: ")
	fmt.Scan(&age)

	// Print the entered values
	fmt.Println("Name: ", name)
	fmt.Println("Age : ", age)
}

Output:

Enter name: Alvin 
Enter age: 21
Name:  Alvin
Age :  21

Example 3:

// Golang program to demonstrate the
// example of fmt.Scan() function
// Input two numbers & find their sum

package main

import (
	"fmt"
)

func main() {
	var num1 int
	var num2 int
	var sum int

	// Input numbers
	fmt.Print("Enter first number: ")
	fmt.Scan(&num1)

	fmt.Print("Enter second number: ")
	fmt.Scan(&num2)

	// Calculate sum
	sum = num1 + num2

	// Printing the values & sum
	fmt.Printf("%d + %d = %d\n", num1, num2, sum)
}

Output:

Enter first number: 108
Enter second number: 101
108 + 101 = 209

Golang fmt Package »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.