Golang – 从结构体数组中的值创建字符串

huangapple go评论75阅读模式
英文:

Golang - Creating a string from value in array of structs

问题

我有一个包含结构体的数组,每个结构体都有一个id和一个title。

创建一个逗号分隔的id列表的最有效方法是什么?

例如:

结构体A - id: 1, title: ....
结构体B - id: 2, title: ....
结构体C - id: 3, title: ....

需要一个字符串 "1,2,3"

英文:

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"

答案1

得分: 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())
}

请注意,这是一个Go语言的代码示例,它迭代一个名为dataCollection的数组,并将其中的id字段附加到一个缓冲区csv中。最后,它打印出缓冲区的内容。

英文:

Iterate the array and append to a buffer.

package main

import (
	&quot;bytes&quot;
	&quot;fmt&quot;
	&quot;strconv&quot;
)

type data struct {
	id   int
	name string
}

var dataCollection = [...]data{data{1, &quot;A&quot;}, data{2, &quot;B&quot;}, data{3, &quot;C&quot;}}

func main() {
	var csv bytes.Buffer
	for index, strux := range dataCollection {
		csv.WriteString(strconv.Itoa(strux.id))
		if index &lt; (len(dataCollection) - 1) {
			csv.WriteString(&quot;,&quot;)
		}
	}
	fmt.Printf(&quot;%s\n&quot;, csv.String())
}

huangapple
  • 本文由 发表于 2014年4月11日 15:35:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/23006343.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定