Basically I have []int{1, 2, 3}
, I want a one-liner that transforms this into the string "1, 2, 3" (I need the delimiter to be custom, sometimes .
, sometimes ,
, etc). Below is the best I could come up with. Searched online and did not seem to find a better answer.
In most languages there is in-built support for this, e.g.:
python:
> A = [1, 2, 3]
> ", ".join([str(a) for a in A])
'1, 2, 3'
go:
package main
import (
"bytes"
"fmt"
"strconv"
)
// Could not find a one-liner that does this :(.
func arrayToString(A []int, delim string) string {
var buffer bytes.Buffer
for i := 0; i < len(A); i++ {
buffer.WriteString(strconv.Itoa(A[i]))
if i != len(A)-1 {
buffer.WriteString(delim)
}
}
return buffer.String()
}
func main() {
A := []int{1, 2, 3}
fmt.Println(arrayToString(A, ", "))
}
Surely there must be an utility buried into go that allows me to do this with a one-liner?
I know that there is strings.Join(A, ", ")
, but that only works if A is already []string.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…