Accessing the next element in a slice

Is there a way of specifying that one wants to access the next (or indeed previous) element in a slice of things. At the moment I have the following functions which are horribly inefficient…

func (n *node) Next() *node {
	if n.Parent != nil {
		i := indexOf(n.Parent.children, n)
		l := len(n.Parent.children)
		if i < (l - 1) {
			return n.Parent.children[i+1]
	return nil

func indexOf(slice []*node, node *node) int {
	for p, v := range slice {
		if v == node {
			return p
	return -1

Also I’m not sure about the validity of the == comparison in the indexOf function. Is this going to work in all cases or am I going to have to look at deeper (in terms of reflection) methods of comparison?

Thanks folks!

I already have a Tree method which iterates the entire structure of a tree by recursively accessing the nodes by carrying out a for range on the node’s children slice, but I was also keen to build a single step method, as it were, of stepping through the nodes using the Next() method.

How about just the standard library package container/list, which is a doubly linked list. find at

1 Like

Hi Cecil, that looks very interesting indeed. Ok I would have to replace the slice based mechanics I have at the moment, but a quick glance at the docs tells me that container/list has all of the other funcs that I will need. In fact I can think of a few uses for it, so thanks very much indeed. It’s getting late so time for bed - something to do tomorrow!

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