doushi1847 2014-04-11 07:35
浏览 27
已采纳

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

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条回答 默认 最新

  • dptrmt4366 2014-04-11 09:06
    关注

    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
    ", csv.String())
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿