Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cleaner way to iterate through array + create a string from values

Tags:

go

With this code, is there a better way to loop through all the users and create a new string containing all their Nick values?

package main

import "fmt"

type User struct {
    Nick     string
}


func main() {
    var users [2]User
    users[0] = User{ Nick: "Radar" }
    users[1] = User{ Nick: "NotRadar" }
    names := ":"
    for _, u := range users {
        names += u.Nick + " "
    }
    fmt.Println(names)

}
like image 834
Ryan Bigg Avatar asked Feb 03 '26 01:02

Ryan Bigg


1 Answers

For example,

package main

import (
    "bytes"
    "fmt"
)

type User struct {
    Nick string
}

func main() {
    var users [2]User
    users[0] = User{Nick: "Radar"}
    users[1] = User{Nick: "NotRadar"}
    var buf bytes.Buffer
    buf.WriteByte(':')
    for _, u := range users {
        buf.WriteString(u.Nick)
        buf.WriteByte(' ')
    }
    names := buf.String()
    fmt.Println(names)
}

This avoids a lot of allocations due to the concatenation of strings.

You could also write:

package main

import (
    "fmt"
)

type User struct {
    Nick string
}

func main() {
    var users [2]User
    users[0] = User{Nick: "Radar"}
    users[1] = User{Nick: "NotRadar"}
    var buf []byte
    buf = append(buf, ':')
    for _, u := range users {
        buf = append(buf, u.Nick...)
        buf = append(buf, ' ')
    }
    names := string(buf)
    fmt.Println(names)
}
like image 132
peterSO Avatar answered Feb 05 '26 13:02

peterSO



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!