I have an array of different values - is there a way to convert it to csv string and output it via fmt.Print
to stdout, without writing the csv to some file?
As far as I know, if I create a csv writer, I have to pass io file as a parameter, is there a way to just output it?
yes:
for string slice:
package main
import "encoding/csv"
import "os"
func main() {
wr := csv.NewWriter(os.Stdout)
wr.Write([]string{"test1", "test2", "test3"})
wr.Flush()
}
for int (or any slice):
package main
import (
"encoding/csv"
"fmt"
"os"
"strings"
)
func main() {
A := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} // []string{"test1", "test2", "test3"}
st := strings.Fields(strings.Trim(fmt.Sprint(A), "[]"))
wr := csv.NewWriter(os.Stdout)
wr.Write(st)
wr.Flush() // 0,1,2,3,4,5,6,7,8,9
}
another way:
package main
import (
//"encoding/csv"
"fmt"
"strings"
)
func main() {
A := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
st := strings.Trim(strings.Join(strings.Fields(fmt.Sprint(A)), ", "), "[]")
fmt.Println(st) // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
}
if your data is not int convert it to slice of string, then use strings.Join function.
and see:
go / golang: one-liner to transform []int into string