Skip to content
Tutorials Center
My learning

Topics

Go Reference ยท strings and strconv

Go strings.Fields() function

Reference for Go strings.Fields, FieldsFunc and FieldsSeq: split text on runs of whitespace or a custom rule, with no empty pieces, and how it differs from Split.

strings.Fields(s) splits s around runs of white space (as defined by unicode.IsSpace) and returns the words in between. Leading, trailing and repeated white space never produce empty strings, which makes it the right tool for tokenizing human-typed text.

FieldsFunc lets you decide what counts as a separator with your own function, and FieldsSeq and FieldsFuncSeq (Go 1.24) return iterators.

Go
words := strings.Fields("  go  is\tfun\n") // ["go" "is" "fun"]

Try it

Go Fields versus Split

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Go FieldsFunc with a custom rule

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Syntax

Go
func Fields(s string) []string
func FieldsFunc(s string, f func(rune) bool) []string
func FieldsSeq(s string) iter.Seq[string]
func FieldsFuncSeq(s string, f func(rune) bool) iter.Seq[string]
Name Description
s The text to split.
f Returns true for runes that are separators. Must be a pure function: results should not depend on call order.

Returns: a slice of non-empty substrings, in order. If s has only white space or is empty, the slice is empty (length 0).

Edge cases: any Unicode space (tab, newline, form feed, non-breaking space U+00A0, U+2003 and so on) counts as a separator for Fields. FieldsSeq and FieldsFuncSeq need Go 1.24 or newer.

Usage notes

  • Fields vs Split(s, " "): Split keeps empty pieces between neighbouring spaces and does not know about tabs or newlines. For free-form text, Fields is almost always what you want.
  • Counting words is len(strings.Fields(s)). It treats punctuation as part of a word; use FieldsFunc if "hello," should become "hello".
  • Pieces share memory with s, like Split.
  • Parsing columns: for command-line style input with quotes, Fields is not enough; use a proper tokenizer or the encoding/csv reader with a custom delimiter.
  • Performance: Fields makes one pass to count and one to slice, so it is efficient, but the iterator variants avoid the slice allocation.
  • Fixed separators with empties preserved (a,,b): use strings.Split() instead.
  • Inverse: strings.Join(words, " ") rebuilds text with single spaces, which normalizes spacing.