Reputation: 2286
I have a an array of structs that each have an id and a title.
What is the most efficient way of creating a comma separated list of ids from this array.
eg
Struct A - id: 1, title: ....
Struct B - id: 2, title: ....
Struct C - id: 3, title: ....
Need a string "1,2,3"
Upvotes: 0
Views: 2820
Reputation: 764
Iterate the array and append to a buffer.
package main
import (
"bytes"
"fmt"
"strconv"
)
type data struct {
id int
name string
}
var dataCollection = [...]data{data{1, "A"}, data{2, "B"}, data{3, "C"}}
func main() {
var csv bytes.Buffer
for index, strux := range dataCollection {
csv.WriteString(strconv.Itoa(strux.id))
if index < (len(dataCollection) - 1) {
csv.WriteString(",")
}
}
fmt.Printf("%s\n", csv.String())
}
Upvotes: 3