I am writing a ray-surface collision function that needs to return small structs (Collision
contains some information about the collision). Currently I am returning the struct by value because I do not need to adjust or share the contents of collision
. However, sometimes the ray will not actually collide, so my function signature currently looks like:
func (scene *Scene) GetFirstCollision(ray *Ray) (Collision, bool)
Where the boolean is false when there is no collision. However, I do not know what value the Collision
should take when there is no collision. If it were a pointer, I would just return nil
, but it isn't, so should I return Collision{}
? If the overall more idiomatic way is just to return a *Collision
and return nil
when it does not exist, I am open to that too, I just can't think of a case when I would ever need a pointer to the collision.
In my humble opinion...
Unless returning a pointer is important to your use case, continue to use the return type of (Collision, bool)
and simply do return Collision{}, false
when there is no collision.
If returning the collision as a pointer is important to your use case, simply return a *Collision
, where the nil
return type signifies "no collision", as you have described.
It is desirable, to my knowledge, for ray-tracing to be quite performant, so you may have a genuine reason to prefer the first option.