3
\$\begingroup\$

I just started learning Go. To start playing with it, I've implemented the fast power algorithm:

Any suggestions or criticisms regarding the coding style?

package main

import (
    "errors"
    "fmt"
    "math"
)

func main() {
    result, ok := fast_power(2, 4)
    if ok != nil {
        fmt.Println("Something went wrong", ok)
    }
    fmt.Println(result)
}

func fast_power(n uint32, power int) (uint32, error) {

    if power < 0 && math.Floor(float64(power)) == float64(power) {
        return uint32(math.NaN()), errors.New("Power must be a positive integer or zero")
    }

    if power == 0 {
        return 1, nil
    }

    var factor uint32
    var result uint32

    mul := func(v uint32) {
        if result == 0 {
            result = v
        } else {
            result *= v
        }
    }

    for factor = n; power > 0; power, factor = power>>1, factor*factor {
        if power&1 == 1 {
            mul(factor)
        }
    }

    return result, nil
}
\$\endgroup\$
1
\$\begingroup\$

If an error type is returned, then the variable you're assigning it to, usually is called err or something similar. An example is shown here.

If instead, a bool type is returned, which is true upon success, then it is called ok. An example is shown here.


You might know that your fast_power function doesn't like getting negative power values, but since I can easily compute 5^(-2), I'm sure there'll be someone who will try to do so with your function. I suggest you document that as well (by means of comments), and not just by throwing an error.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.