[idiomatic Go] tree.Find(val int) should return (Node, error) VS (Nod, bool) VS (*Node)?

Hi all,

a tree pakcage that implements a type of binary tree, has a method find(val int) which should return the actual node that contains val.

How should the signature of this function look like: what should I return when val is not contained in that tree:
func (m *myTree) Find(val int) (Node, error)
func (m *myTree) Find(val int) (Node, bool)
func (m *myTree) Find(val int) *Node

In short, this function returns a node or the information that there. is no node containing the searched for value. What option is more idiomatic to Go ?

And make the *Node returned nil if no node is found.

1 Like

Tank you @lutzhorn ! This makes sense, the pointer also holds the information that the value exists or not, by being nil or not.

How would this. approach change if, instead of an object result there would be an int result. For example, lets say a stack has the Pop() and Peek() operations. They return an int, but if the stack is empty they should return an error, or perhaps a bool ?

func (s *stack) Pop() (int, error)
func (s *stack) Pop() (int, bool)

As the stack can hold any int, 0 is a legitimate value, so it cannot signify the stack is empty scenario. What is the best approach here ?

This. Take a look at how a map works:

m := make(map[int]int)

i, ok := m[123]
if ok {
  fmt.Println(i)
}

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