ZetCode

Go join string

last modified October 30, 2026 Go 1.27

In this article we show how to join strings in Go. Joining means collecting several values into one string, usually with a separator between them.

The standard library offers the following tools:

All examples in this article were compiled and run with Go 1.27.0.

Joining a slice with strings.Join

strings.Join concatenates the elements of a string slice and inserts the separator between them. It allocates the result once, so its cost is linear in the total length of the output.

func Join(elems []string, sep string) string

That is the whole signature: a slice and a separator, with no error to check.

main.go
package main

import (
    "fmt"
    "strings"
)

func main() {

    words := []string{"an", "old", "falcon"}

    fmt.Println(strings.Join(words, " "))
    fmt.Println(strings.Join(words, ", "))
    fmt.Println(strings.Join(words, ""))
}

The three calls use the same slice with different separators. The last one concatenates the elements without any separator, which is the fastest way to merge a slice of strings.

$ go run main.go
an old falcon
an, old, falcon
anoldfalcon

Edge cases of strings.Join

The separator is placed only between elements. A slice with one element returns that element unchanged, and an empty slice returns an empty string even when the separator is not empty.

main.go
package main

import (
    "fmt"
    "strings"
)

func main() {

    fmt.Printf("%q\n", strings.Join([]string{}, ", "))
    fmt.Printf("%q\n", strings.Join(nil, ", "))
    fmt.Printf("%q\n", strings.Join([]string{"only"}, ", "))
    fmt.Printf("%q\n", strings.Join([]string{"", ""}, ","))
}

A nil slice and an empty slice behave the same way, so no nil check is needed before the call. Two empty elements are still two elements, which is why the separator appears in the last result.

$ go run main.go
""
""
"only"
","

Joining values that are not strings

strings.Join accepts only []string. Numbers, structs and other values must be converted first. Converting into a preallocated slice keeps the loop to a single allocation.

main.go
package main

import (
    "fmt"
    "strconv"
    "strings"
)

func joinInts(nums []int, sep string) string {

    parts := make([]string, len(nums))

    for i, n := range nums {
        parts[i] = strconv.Itoa(n)
    }

    return strings.Join(parts, sep)
}

func main() {

    fmt.Println(joinInts([]int{1, 2, 3}, ", "))
    fmt.Println(joinInts([]int{5}, " - "))
    fmt.Printf("%q\n", joinInts(nil, ", "))
}

The helper works for any slice of numbers; the conversion is the only part that depends on the element type. Go 1.23 added generic helpers such as slices.Collect, which turns an iterator into a slice, but a plain loop is still the clearest way to convert and join at the same time.

$ go run main.go
1, 2, 3
5
""

Joining with strings.Builder

When the pieces are not already in a slice, a strings.Builder appends them one by one. The separator is written before every element except the first one, which avoids a trailing separator.

main.go
package main

import (
    "fmt"
    "strconv"
    "strings"
)

func joinInts(nums []int, sep string) string {

    var sb strings.Builder

    for i, n := range nums {
        if i > 0 {
            sb.WriteString(sep)
        }
        sb.WriteString(strconv.Itoa(n))
    }

    return sb.String()
}

func main() {

    fmt.Println(joinInts([]int{3, 1, 4}, " | "))
    fmt.Println(joinInts([]int{2, 7, 1, 8}, ""))
}

This version does not build an intermediate slice, so it uses less memory than the converting helper above when the values are expensive to store. For values that are already strings, strings.Join does the same job: it also writes the separator only between elements, and it allocates the result once.

$ go run main.go
3 | 1 | 4
2718

Joining with bytes.Buffer

A bytes.Buffer is a growable byte buffer with both write and read methods. It is a drop-in alternative to strings.Builder when the data is treated as bytes.

main.go
package main

import (
    "bytes"
    "fmt"
)

func main() {

    var buf bytes.Buffer

    buf.WriteString("an ")
    buf.WriteString("old ")
    buf.WriteString("falcon")

    fmt.Println(buf.String())
    fmt.Println(buf.Len())
}

String returns the accumulated content and Len returns its size in bytes. Unlike a builder, the buffer can also be read from, which is useful when the same value is written and then parsed.

$ go run main.go
an old falcon
13

Joining with fmt.Sprintf, Sprint and Sprintln

The fmt functions join values without a separator argument: the format string supplies the text between them. Sprint inserts a space only between operands when neither is a string, and Sprintln always separates with spaces and appends a newline.

main.go
package main

import "fmt"

func main() {

    w1, w2 := "old", "falcon"

    fmt.Println(fmt.Sprintf("%s %s", w1, w2))

    fmt.Printf("%q\n", fmt.Sprint(w1, " ", w2))
    fmt.Printf("%q\n", fmt.Sprint(w1, 3, true))
    fmt.Printf("%q\n", fmt.Sprint(3, true, w1))
    fmt.Printf("%q\n", fmt.Sprintln(w1, 3))
}

The quoted results make the spacing rules visible. A string operand suppresses the automatic space, so Sprint("old", 3, true) produces "old3 true": the space appears only between the two non-string values.

$ go run main.go
old falcon
"old falcon"
"old3 true"
"3 trueold"
"old 3\n"

Joining struct fields with a String method

A type that implements String() string decides how it is printed. strings.Join builds the representation, and the method is used automatically by every fmt verb, including the Println of a slice of users.

main.go
package main

import (
    "fmt"
    "strings"
)

type User struct {
    Name       string
    Occupation string
}

func (u User) String() string {
    return strings.Join([]string{u.Name, "is a", u.Occupation}, " ")
}

func main() {

    users := []User{
        {"John Doe", "gardener"},
        {"Roger Roe", "driver"},
    }

    for _, u := range users {
        fmt.Println(u)
    }

    fmt.Println(users)
}

The loop prints one user per line. The last statement passes the whole slice, and because each element has a String method, the slice is printed as a bracketed list of those strings rather than as a list of structs.

$ go run main.go
John Doe is a gardener
Roger Roe is a driver
[John Doe is a gardener Roger Roe is a driver]

Joining sorted map keys

Map iteration order is not defined, so joining the keys of a map directly would produce a different string on every run. Sorting the keys first makes the output reproducible.

main.go
package main

import (
    "fmt"
    "maps"
    "slices"
    "strings"
)

func main() {

    langs := map[string]string{
        "go":     "Go",
        "python": "Python",
        "rust":   "Rust",
        "c":      "C",
    }

    keys := slices.Sorted(maps.Keys(langs))

    names := make([]string, 0, len(keys))
    for _, k := range keys {
        names = append(names, langs[k])
    }

    fmt.Println(strings.Join(keys, ", "))
    fmt.Println(strings.Join(names, " / "))
}

maps.Keys returns an iterator and slices.Sorted collects and sorts it in one step. Both lines of output are therefore the same on every run.

$ go run main.go
c, go, python, rust
C / Go / Python / Rust

Normalizing whitespace with Fields and Join

strings.Fields splits a string around runs of whitespace and drops empty fields. Joining the fields back with a single space collapses all repeated and leading spaces, which is a common clean-up for data read from a file.

main.go
package main

import (
    "fmt"
    "strings"
)

func main() {

    line := "  falcon   sky  earth "
    fields := strings.Fields(line)

    fmt.Println(len(fields))
    fmt.Printf("%q\n", strings.Join(fields, " "))
    fmt.Printf("%q\n", strings.Join(strings.Split("a,b,,c", ","), " | "))
}

Fields produced three elements, so the cleaned line has single spaces. The second expression shows the contrast with strings.Split, which keeps empty fields: "a,b,,c" yields four elements, and the empty one becomes an empty column.

$ go run main.go
3
"falcon sky earth"
"a | b |  | c"

Building SQL placeholders

A frequent use of Join is generating a list of placeholders for an IN clause. The number of placeholders must match the number of arguments passed to the query.

main.go
package main

import (
    "fmt"
    "strconv"
    "strings"
)

func placeholders(n int) string {

    parts := make([]string, n)
    for i := range parts {
        parts[i] = "?"
    }

    return strings.Join(parts, ", ")
}

func main() {

    fmt.Printf("%q\n", placeholders(3))

    q := "SELECT * FROM cities WHERE id IN (" + placeholders(3) + ")"
    fmt.Println(q)

    ids := []int{3, 7, 11}
    vals := make([]string, len(ids))
    for i, id := range ids {
        vals[i] = strconv.Itoa(id)
    }

    fmt.Println("... (" + strings.Join(vals, ", ") + ")")
}

The placeholders themselves contain no data, so the query text is the same for any values; only the argument list changes. The last line shows how the literal values would look in a SELECT used for debugging.

$ go run main.go
"?, ?, ?"
SELECT * FROM cities WHERE id IN (?, ?, ?)
... (3, 7, 11)

Joining filesystem paths

filepath.Join looks similar but performs a different job: it cleans the result, removes duplicate separators and uses the separator of the current operating system. It must never be used for text that happens to contain slashes.

main.go
package main

import (
    "fmt"
    "path"
    "path/filepath"
)

func main() {

    fmt.Println(filepath.Join("home", "user", "docs", "file.txt"))
    fmt.Println(filepath.Join("home", "", "docs"))
    fmt.Println(filepath.Join("home/", "/docs/", "file.txt"))
    fmt.Println(path.Join("api", "v1", "users"))
}

Empty elements are ignored, and adjacent separators are collapsed. Note that an absolute element does not reset the path, as it does in some other languages: the third call keeps the home prefix. path.Join is the slash-only variant, used for URLs and import paths.

$ go run main.go
home/user/docs/file.txt
home/docs
home/docs/file.txt
api/v1/users

Joining CSV rows

For delimited data, encoding/csv handles quoting and escaping that a plain strings.Join would get wrong. The writer accepts an io.Writer, so a strings.Builder captures the result in memory.

main.go
package main

import (
    "encoding/csv"
    "fmt"
    "os"
    "strings"
)

func main() {

    rows := [][]string{
        {"name", "city", "population"},
        {"Bratislava", "Bratislava", "432000"},
        {"Prague", "Prague", "1280000"},
    }

    var sb strings.Builder
    w := csv.NewWriter(&sb)

    if err := w.WriteAll(rows); err != nil {
        fmt.Fprintln(os.Stderr, err)
        return
    }

    fmt.Print(sb.String())
    fmt.Println(strings.Count(sb.String(), "\n"), "lines")
}

WriteAll flushes the writer, so the builder already holds the complete text when it returns. Each record ends with a newline, which is why the line count equals the number of records.

$ go run main.go
name,city,population
Bratislava,Bratislava,432000
Prague,Prague,1280000
3 lines

Join versus repeated concatenation

Strings are immutable, so every += in a loop copies the text accumulated so far. The total work grows with the square of the number of elements, and so does the garbage. strings.Join measures the required size first, allocates once, and copies each element once.

main.go
package main

import (
    "fmt"
    "strconv"
    "strings"
)

func main() {

    n := 5

    slow := ""
    for i := 0; i < n; i++ {
        if i > 0 {
            slow += "-"
        }
        slow += strconv.Itoa(i)
    }

    parts := make([]string, n)
    for i := range parts {
        parts[i] = strconv.Itoa(i)
    }

    fmt.Println(slow)
    fmt.Println(strings.Join(parts, "-"))
    fmt.Println(slow == strings.Join(parts, "-"))
}

Both approaches produce the same text for a handful of elements. The difference only becomes visible with thousands of iterations, where the quadratic copying of += dominates the running time.

$ go run main.go
0-1-2-3-4
0-1-2-3-4
true

Source

Go strings package - reference

In this article we have joined strings with strings.Join, strings.Builder, bytes.Buffer and the fmt formatting functions, and we have distinguished filepath.Join from text joining.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Go tutorials.