Skip to content
Tutorials Center
My learning

Topics

Go Reference ยท strings and strconv

Go strings.Join() function

Reference for Go strings.Join: concatenate a slice of strings with a separator, how it handles empty and single-element slices, and when to use Builder instead.

strings.Join(elems, sep) concatenates the elements of a []string into one string, placing sep between neighbours. It is the inverse of strings.Split() and is the idiomatic way to build comma lists, paths and sentences.

It computes the final size first and allocates once, so it is much faster than adding strings in a loop.

Go
s := strings.Join([]string{"a", "b", "c"}, "-") // "a-b-c"

Try it

Go Joining slices

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 Joining non-strings

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 Join(elems []string, sep string) string
Name Description
elems The strings to join. May be nil or empty.
sep Text inserted between consecutive elements. May be empty.

Returns: the joined string. An empty or nil slice gives ""; a one-element slice gives that element unchanged (no separator).

Edge cases: empty elements are kept, so []string{"", ""} joined with "," is ",". The separator is never added at the start or end. Join does not panic, apart from the improbable case of a result too large for memory.

Usage notes

  • Only []string. Go has no generic join over other slice types. Convert elements first (as in the second example) with strconv.Itoa, fmt.Sprint or a small loop.
  • Don't put a separator on the last element yourself. Loops that append ", " need cleanup afterwards; Join avoids that.
  • Joining in a loop with += copies the whole string every time, giving quadratic behavior. Join or strings.Builder are both linear.
  • Building file paths: use path.Join or filepath.Join, which also clean duplicate slashes and ...
  • Escaping: Join does not quote or escape. If elements may contain the separator, the result cannot be split back reliably; use encoding/csv or JSON.
  • Efficiency: one allocation for the result, plus nothing else. Pre-size when you build the []string with make([]string, 0, n).
  • Skipping empties needs a filter first; Join keeps them on purpose.