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 华为nova10pro ,关闭热动热点用量记录
  • ¥15 JavaFX启动SceneBuilder报错,找不到fxml文件
  • ¥15 树莓派ubuntu使用conda就提示core dumped
  • ¥15 帮我看看这是个啥题,带解题过程和结果,条件如下FCF = 290471.33 g1 = 15% r = 8% g2 = 4% n = 5
  • ¥15 edem模拟颗粒不显示或者生成失败
  • ¥15 Python代码编写
  • ¥15 php 将rtmp协议转hls协议,无法播放
  • ¥20 python代码编写
  • ¥20 使用MPI广播数据遇到阻塞
  • ¥15 TinyMCE如何去掉自动弹出的“链接…”工具?