Newbie's vector code

Could somebody look at this code:

What are the visible places where it could be better? I don’t like comparing err with nil 2 times in calculating angle, what’s the best way to fix it? Do I have to pass vector pointer as a receiver for optimization or it’ll make it worse, because you might think I’m going to change vector?

The biggest problem that I see with this is making a type with a single field. Just type directly:
type Vector []float64

Might also want to use camelCase instead of snake_case for your private function names as well.

1 Like

I don’t like comparing err with nil 2 times

Explicit error checking is considered a feature in Go. You need to think about the errors your code generates, and how to handle them or pass them on. With exceptions, it is just too easy to ignore errors and have them “bubble up” through the call chain. Then the top level of your code spits out a low-level error message that is not very helpful at that point.

To make explicit error checking useful, add context before returning an error.

Instead of

if err != nil {
    return err
}

write sth. like

if err != nil {
    return fmt.Errorf("Unable to calculate angle: %s", err)
}

If you create different texts for each of the two errors, you can later track down the cause of an error much easier than without context.

2 Likes

In addition to what Christopher has said, in Go error messages can be chainable. So, it’s better to use all lowercase letters in error messages, like this:

if err != nil {
    return fmt.Errorf("unable to calculate angle: %s", err)
}