Any chance to use math.Abs without converting my value to float64?

Hi all,

I have a lot of lines in my code using math.Abs, like this:

math.Abs(float64(resultA-resultB))

This produces long lines of code (especially when comapring one math.Abs with another). Is there any advice on how to get past this ? How can I refactor, for example, this line ?

		if math.Abs(float64(current.(element).value-maxValue)) <
		math.Abs(float64(resultA-resultB)) {

You could make a function that does it. Assuming the values you’re converting to float64s are ints:

func abs(v int) float64 {
    return math.Abs(float64(v))
}

func main() {
    // ...
    meaningfulName1 := abs(current.(element).value-maxValue)
    meaningfulName2 := abs(resultA-resultB)
    if meaningfulName1 < meaningfulName2 {
        // ...
    }
}

EDIT: Forgot abs's return value!

are store the elements as float64 :slight_smile: is there any particular reason why you don’t want to do that?

@bklimczak has a good point- if you don’t want to store the values as float64s, then you should just implement abs as this:

func abs(v int) int {
	if v < 0 {
		return -v
	}
	return v
}

So that you’re not needlessly converting the values to float64s.

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