0

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 Answer 1

3

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())
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.