Golang has the three dot operator (...) which dumps each element of a slice as its own argument when used with a function call, but it seems that a similar mechanic can't be used with a struct initializer.
Is there a way to reduce code clutter by not accessing every element in a slice when initializing a struct?
Is it possible to append a value to a initialized struct one by one or access an index of some sort inside a for loop?
(I suppose it would be possible to access the direct memory location of a initialized struct - but I'd prefer not to do that)
The following doesn't work: (syntax error)
type Stats struct {
Total uint64
ICMP uint64
UDP uint64
TCP uint64
FTP uint64
HTTP uint64
MAIL uint64
P2P uint64
}
func newStats(slice [][]byte) *Stats {
var tmp [8]uint64
var err error
for i, val := range slice {
tmp[i], err = strconv.ParseUint(string(val), 10, 32)
if err != nil {
// Handle error
}
}
return &Stats{tmp...} // Syntax error
}
Neither does this: (of course)
return &Stats{
for{ <code> }
}
This works, but I'd hope for a idiomatic, faster way, without syntax copying
return &Stats{
tmp[0],
tmp[1],
tmp[2],
tmp[3],
tmp[4],
tmp[5],
tmp[6],
tmp[7],
}