[Go] Write CSV records to a string

Created on November 30, 2026

You can write CSV records to a bytes.Buffer with Go's encoding/csv package, then read the buffer as a string.

package main

import (
    "bytes"
    "encoding/csv"
    "fmt"
)

func main() {
    records := [][]string{
        {"name", "age", "country"},
        {"Tanaka", "20", "Japan"},
        {"Bob", "25", "USA"},
        {"Tom", "30", "England"},
    }

    var buf bytes.Buffer
    w := csv.NewWriter(&buf)
    if err := w.WriteAll(records); err != nil {
        panic(err)
    }

    fmt.Print(buf.String())
}

WriteAll writes each record and flushes the writer. buf.String() returns the resulting CSV text.

name,age,country
Tanaka,20,Japan
Bob,25,USA
Tom,30,England
Go