Golang fmt.Sscan() Function with Examples

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

fmt.Sscan()

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

It accepts two parameters (str string, a ...interface{}) and returns the number of total items successfully parsed and an error if occurred during paring.

Syntax:

func Sscan(str string, a ...interface{}) (n int, err error)

Parameter(s):

  • str : It contains the argument string to be extracted.
  • 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.Sscan() function is a string, it returns the number of total items successfully parsed and an error if occurred during paring.

Example 1:

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

package main

import (
	"fmt"
)

func main() {
	var x int
	var y int

	// Scans the values (space-separated)
	// and assigns to the variables
	fmt.Sscan("10 20", &x, &y)

	// Prints the values
	fmt.Println("x:", x)
	fmt.Println("y:", y)

	// Scans the values (newline-separated)
	// and assigns to the variables
	fmt.Sscan("30\n40", &x, &y)

	// Prints the values
	fmt.Println("x:", x)
	fmt.Println("y:", y)

	// Scans the values (Tab-separated)
	// and assigns to the variables
	fmt.Sscan("50\t60", &x, &y)

	// Prints the values
	fmt.Println("x:", x)
	fmt.Println("y:", y)
}

Output:

x: 10
y: 20
x: 30
y: 40
x: 50
y: 60

Example 2:

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

package main

import (
	"fmt"
)

func main() {
	// Assign the value to a string variable
	data := "Alex 21 98.50"

	// Declare the variables to store the values
	var name string
	var age int
	var perc float32

	// Scans the values and assigns
	// to the variables
	fmt.Sscan(data, &name, &age, &perc)

	// Prints the values
	fmt.Println("Name:", name)
	fmt.Println("Age:", age)
	fmt.Println("Percentage:", perc)
}

Output:

Name: Alex
Age: 21
Percentage: 98.5

Golang fmt Package »




Comments and Discussions!

Load comments ↻





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