How to print slice of structs, only the payload of each struct

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()

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

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.