0
我有一個結構數組,每個結構都有一個id和一個標題。Golang - 從結構數組中創建一個字符串
什麼是從這個數組中創建逗號分隔的ID列表的最有效的方式。
例如
Struct A - id: 1, title: ....
Struct B - id: 2, title: ....
Struct C - id: 3, title: ....
需要一個串"1,2,3"
我有一個結構數組,每個結構都有一個id和一個標題。Golang - 從結構數組中創建一個字符串
什麼是從這個數組中創建逗號分隔的ID列表的最有效的方式。
例如
Struct A - id: 1, title: ....
Struct B - id: 2, title: ....
Struct C - id: 3, title: ....
需要一個串"1,2,3"
迭代陣列和附加到一個緩衝區中。
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())
}