How to Use fmt.Sscan() Function in Golang

The fmt.Sscan() function in Go is used to scan the specified texts and store the successive space-separated texts into successive arguments.

Syntax

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

Parameters

  1. src: The source from where the input is to be taken. This should be an object of type string.
  2. a …interface{}: The list of all arguments you want to store data.

Return value

It can return two values:

  1. count: It returns several arguments the function writes to.
  2. err: Any error thrown during the execution of the function.

Example 1

package main

import (
  "fmt"
)

func main() {
  var a int
  var b string
  var c float64
  input := "5 Golang 3.14"

  // Read the input string and store the values in a, b, and c
  n, err := fmt.Sscan(input, &a, &b, &c)
  if err != nil {
    fmt.Println("Error:", err)
    return
  }

  fmt.Printf("Parsed %d values\n", n)
  fmt.Printf("a: %d, b: %s, c: %f\n", a, b, c)
}

Output

Parsed 3 values

a: 5, b: Golang, c: 3.140000

Example 2

package main

import (
  "fmt"
)

func main() {
  var city string
  var population int
  var area float64
  var isCapital bool

  input := "NewYork 8419000 468.9 false"

  n, err := fmt.Sscan(input, &city, &population, &area, &isCapital)
  if err != nil {
    panic(err)
  }

  fmt.Printf("%d: %s, %d, %g, %t\n", n, city, population, area, isCapital)
}

Output

4: NewYork, 8419000, 468.9, false

That’s it.