Cannot convert <type1> to <type2> error in Golang

In Golang, the "cannot convert <type1> to <type2>" error occurs when you try to convert a value of one type to a value of another type, but the conversion is not allowed. This error indicates that there is a type mismatch between the source and destination types, and the conversion cannot be performed.

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

Example

package main

import "fmt"

func main() {
    var num1 int = 123
    var num2 float64 = float64(num1)
    fmt.Println(num2)
}

In this program, we declare a variable num1 of type int and initialize it with the value 123. We then declare another variable num2 of type float64 and try to assign the value of num1 to num2 after converting num1 to a float64 value using the float64() function. The fmt.Println() function is then used to print the value of num2 to the console.

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

Output

./main.go:7:25: cannot convert num1 (type int) to type float64

This error occurs because we are trying to convert an int value to a float64 value, but the conversion is not allowed. To fix this error, we need to use a type conversion function or syntax that is appropriate for the types involved. In this case, we can simply change the type of num1 to float64, like this:


Example

package main

import "fmt"

func main() {
    var num1 float64 = 123
    var num2 float64 = num1
    fmt.Println(num2)
}

In this modified program, we declare the num1 variable as a float64 value instead of an int value. We then assign the value of num1 to num2 without any conversion because both variables are of the same type. This code will compile and run without any errors.

In summary, the "cannot convert <type1> to <type2>" error in Golang occurs when you try to convert a value of one type to a value of another type, but the conversion is not allowed. To fix this error, you need to use a type conversion function or syntax that is appropriate for the types involved or change the type of the variables involved to match each other.


Most Helpful This Week