fmt Fscan Tokens From Readers

fmt.Fscan pulls whitespace-separated tokens from any reader and converts them by pointer type, so parsing does not need a fixed layout.

GoData Integrity

Code

gosnippet
27 lines
package main

import (
	"fmt"
	"strings"
)

func main() {
	input := strings.NewReader("192.168.1.10 8080")

	var host string
	var port int
	// Fscan pulls tokens from readers: whitespace-separated, converted by type
	if _, err := fmt.Fscan(input, &host, &port); err != nil {
		panic(err)
	}
	fmt.Printf("host=%s port=%d\n", host, port)

	more := strings.NewReader("42 3.14 ok")
	var n int
	var ratio float64
	var label string
	if _, err := fmt.Fscan(more, &n, &ratio, &label); err != nil {
		panic(err)
	}
	fmt.Println(n, ratio, label)
}

Inside the snippet

fmt Fscan Tokens From Readers is built around the function main.

err is tested at 2 places, and a non-nil one aborts the run with panic(err).

Points of care

  • Every call resolves to a built-in API — no package manager ever runs.
  • The snippet does not return errors — any non-nil err ends the run immediately.

Putting it to use

Signature: func main()

The run emits 1 labeled section — host= — one per step.

The core lines of the flow

input := strings.NewReader("192.168.1.10 8080")

Interactive Tools for This Topic

FAQ

Does the snippet panic on failure?
It stops. All 2 `if err != nil` branches ends in `panic(err)` — nothing continues past a failed call.
What does fmt Fscan Tokens From Readers print when run?
Invoke the file as-is — the `host=` prefixes identify which step printed each line.