Format and scan values with fmt
Format and scan values with fmt
Use fmt.Sprintf to construct formatted text without printing it. Format verbs describe the representation: %s for a string, %d for a decimal integer, %.2f for two decimal places, and %q for quoted text. Use fmt.Sscanf when a small, known text pattern must be read into variables.
package main
import ( "fmt")
func main() { line := fmt.Sprintf("%s: %d items, %.2f kg", "Box", 3, 2.5) fmt.Println(line) fmt.Printf("%q\n", "a b")}Sprintf returns a string; Printf writes formatted output and returns a byte count and error. Formatting rounds the displayed number, not the stored float. Keep the format string fixed when printing arbitrary user text; use fmt.Printf("%s", text) rather than treating the text as a format string.
Expected output:
Box: 3 items, 2.50 kg"a b"Check scan counts and errors
package main
import ( "fmt")
func read(s string) (int, int, error) { var a, b int n, err := fmt.Sscanf(s, "%d %d", &a, &b) if err != nil { return 0, n, err } return a + b, n, nil}func main() { sum, n, err := read("4 7") fmt.Println(sum, n, err == nil) _, n, err = read("4 bad") fmt.Println(n, err != nil)}Sscanf takes pointers to destination variables and reports the number successfully scanned. A partial result can exist alongside an error; this function discards the sum on failure. Scanning a prefix is not a guarantee that the entire input was consumed; use a stricter parser if trailing data must be rejected.
Expected output:
11 2 true1 trueTry it locally
Read "7 3" into two ints with Sscanf; after checking the count and error, format their product as "total=21".
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Core library 01: Format and scan values with fmt
Check the lesson objective before moving on.
Which function returns formatted text instead of writing it?
If Sscanf reads one of two requested integers before failing, what should you check?