Cannot use <variable> as <type> value in return statement error in Golang

In Golang, the "cannot use <variable> as <type> value in return statement" error occurs when you try to return a value of the wrong type from a function. This error indicates that the return value of the function does not match the expected return type.

Let's consider an example to understand this error. Consider the following Golang program:

Example

package main

import "fmt"

func calculateSum(a, b int) float64 {
    sum := a + b
    return sum
}

func main() {
    result := calculateSum(10, 20)
    fmt.Println("The sum is: ", result)
}

In this program, we define a function calculateSum that takes two integer arguments a and b, calculates their sum, and returns the sum as a float64 value. We then call this function with the values 10 and 20 in the main() function.

However, when we try to compile and run this program, we will encounter the following error:

Output

./main.go:6:9: cannot use sum (type int) as type float64 in return statement

This error occurs because we are trying to return an integer value as a float64 value, which is not allowed. To fix this error, we need to convert the sum variable to a float64 value before returning it, like this:


Example

package main

import "fmt"

func calculateSum(a, b int) float64 {
    sum := float64(a + b)
    return sum
}

func main() {
    result := calculateSum(10, 20)
    fmt.Println("The sum is: ", result)
}

In this modified program, we convert the sum variable to a float64 value before returning it. This code will compile and run without any errors.

In summary, the "cannot use <variable> as <type> value in return statement" error in Golang occurs when you try to return a value of the wrong type from a function. To fix this error, you need to convert the value to the expected return type before returning it.


Most Helpful This Week