patterngoMinor
Fast power in Go
Viewed 0 times
fastpowerstackoverflow
Problem
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?
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; power, factor = power>>1, factor*factor {
if power&1 == 1 {
mul(factor)
}
}
return result, nil
}Solution
If an
If instead, a
You might know that your
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.Context
StackExchange Code Review Q#75837, answer score: 2
Revisions (0)
No revisions yet.