Golang fmt.Sscan function
last modified May 8, 2025
This tutorial explains how to use the fmt.Sscan
function in Go.
We'll cover string parsing basics with practical examples of formatted input.
The fmt.Sscan function scans a string and stores successive space-separated values into arguments. It returns the number of items successfully scanned and any error encountered.
In Go, fmt.Sscan
is useful for parsing simple string data into
variables. It's part of the fmt package which handles formatted I/O operations.
Basic fmt.Sscan example
The simplest use of fmt.Sscan
parses space-separated values from
a string. This example demonstrates basic string scanning.
Note: Values must be space-separated in the input string.
package main import ( "fmt" ) func main() { var name string var age int input := "John 42" n, err := fmt.Sscan(input, &name, &age) if err != nil { fmt.Println("Error scanning:", err) return } fmt.Printf("Scanned %d values: %s is %d years old\n", n, name, age) }
The code scans two values from the input string into variables. The function returns the count of successfully scanned items and any error.
Scanning multiple values
fmt.Sscan
can parse multiple values of different types from a
string. This example shows scanning various data types.
package main import ( "fmt" ) func main() { var ( name string age int height float64 active bool ) input := "Alice 25 1.68 true" n, err := fmt.Sscan(input, &name, &age, &height, &active) if err != nil { fmt.Println("Error scanning:", err) return } fmt.Printf("Scanned %d values:\n", n) fmt.Printf("Name: %s\nAge: %d\nHeight: %.2f\nActive: %t\n", name, age, height, active) }
The example scans string, integer, float, and boolean values from a single string. Each value must match the expected type in the variable.
Handling scanning errors
When input doesn't match expected types, fmt.Sscan
returns an
error. This example demonstrates error handling.
package main import ( "fmt" ) func main() { var count int var price float64 inputs := []string{ "5 9.99", // valid "five 9.99", // invalid "5 nine", // invalid } for _, input := range inputs { n, err := fmt.Sscan(input, &count, &price) if err != nil { fmt.Printf("Error scanning '%s': %v\n", input, err) continue } fmt.Printf("Scanned %d items from '%s': %d, %.2f\n", n, input, count, price) } }
The code attempts to scan different input strings. Invalid inputs produce errors that we handle gracefully in the program.
Scanning into a struct
We can use fmt.Sscan
to populate struct fields from a string.
This example shows structured data parsing.
package main import ( "fmt" ) type Person struct { Name string Age int City string } func main() { var p Person input := "Bob 35 NewYork" n, err := fmt.Sscan(input, &p.Name, &p.Age, &p.City) if err != nil { fmt.Println("Error scanning:", err) return } fmt.Printf("Scanned %d fields into struct:\n%+v\n", n, p) }
The example scans values directly into a struct's fields. The struct must have exported fields (capitalized names) to be accessible.
Using Sscan with variadic parameters
We can create flexible scanning functions using variadic parameters with
fmt.Sscan
. This example shows a reusable scanning function.
package main import ( "fmt" ) func scanValues(input string, values ...interface{}) error { n, err := fmt.Sscan(input, values...) if err != nil { return err } if n != len(values) { return fmt.Errorf("expected %d values, got %d", len(values), n) } return nil } func main() { var id int var name string var score float64 input := "101 Alice 95.5" err := scanValues(input, &id, &name, &score) if err != nil { fmt.Println("Error:", err) return } fmt.Printf("ID: %d, Name: %s, Score: %.1f\n", id, name, score) }
The scanValues
function accepts any number of pointers to scan
into. It provides additional validation of the scanned item count.
Scanning with custom delimiters
While fmt.Sscan
uses spaces by default, we can pre-process
strings to handle other delimiters. This example shows comma-separated parsing.
package main import ( "fmt" "strings" ) func main() { var item string var quantity int var price float64 input := "apple,5,1.99" // Replace commas with spaces normalized := strings.ReplaceAll(input, ",", " ") n, err := fmt.Sscan(normalized, &item, &quantity, &price) if err != nil { fmt.Println("Error scanning:", err) return } fmt.Printf("Scanned %d items: %d %s at $%.2f each\n", n, quantity, item, price) }
The code converts commas to spaces before scanning. This technique works for
simple cases but consider strings.Split
for complex parsing.
Advanced scanning with Sscanf
For more control over parsing, fmt.Sscanf
offers formatted
scanning. This example compares Sscan and Sscanf.
package main import ( "fmt" ) func main() { var a, b, c int input := "10-20-30" // Using Sscan (requires space separation) n1, err1 := fmt.Sscan(strings.ReplaceAll(input, "-", " "), &a, &b, &c) fmt.Printf("Sscan: %d,&v → %d %d %d\n", n1, err1, a, b, c) // Using Sscanf with format string n2, err2 := fmt.Sscanf(input, "%d-%d-%d", &a, &b, &c) fmt.Printf("Sscanf: %d,&v → %d %d %d\n", n2, err2, a, b, c) }
fmt.Sscanf
provides more precise control with format specifiers.
Choose between Sscan and Sscanf based on your parsing needs.
Source
This tutorial covered the fmt.Sscan
function in Go with practical
examples of string parsing and formatted input handling.
Author
List all Golang tutorials.