const declaration - How to evaluate expressions at compile time?

43 Views Asked by At

In the below code:

package main

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

func area(r float64, shapeConstant float64, result *float64) error {
    if r <= 0 {
        return errors.New("r must be positive")
    }
    *result = shapeConstant * r * r
    return nil
}

const (
    shapeConstantForSquare  = 1.0
    shapeConstantForCircle  = math.Pi
    shapeConstantForHexagon = 3 * math.Sqrt(3) / 2         // 3 * 1.73205080757 / 2
)

func areaOfSquare(r float64, result *float64) error {
    return area(r, shapeConstantForSquare, result)
}

func areaOfCircle(r float64, result *float64) error {
    return area(r, shapeConstantForCircle, result)
}

func areaOfHexagon(r float64, result *float64) error {
    return area(r, shapeConstantForHexagon, result)
}

func main() {
    var result float64
    err := areaOfSquare(3, &result)
    display(err, &result)
    areaOfCircle(3, &result)
    display(err, &result)
    areaOfHexagon(3, &result)
    display(err, &result)
}

func display(err error, result *float64) {
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(*result)
}

const shapeConstantForHexagon = 3 * math.Sqrt(3) / 2 needs runtime to evaluate expression(RHS) and provide value to LHS. Compile error.

How to avoid expression evaluation in RHS, at runtime? in const declaration

Does below expression evaluation lose precision?

const(
    sqrtOfThree             = 1.73205080757
    shapeConstantForHexagon = 3 * sqrtOfThree / 2 
)
0

There are 0 best solutions below