type Node struct {
payload intl
left, right *Node
}
I have a slice of Node: var nodes []Node
How do I priont only the payloads, of the nodes in this struct, separated by a comma ?
Currently I do:
result := ""
for i := range nodes {
result += strconv.Itoa(nodes[i].payload) + " "
}
But I am sure it can be done better or shorter. Any idea ?
Better use strings.Builder to concatenate strings in a loop
var sb strings.Builder
for _, node := range nodes {
sb.WriteString(strconv.Itoa(node.payload))
sb.WriteString(" ")
}
result := sb.String()
imatmati
(Ivan Matmati)
July 29, 2019, 1:27pm
3
Hi,
It seems you forgot that any node of your slice of Node can have a left and right node too and not necessarily present in your slice ! Think recursion.
1 Like
system
(system)
Closed
October 27, 2019, 1:27pm
4
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.