Cannot use <variable> (type <type>) as type <new-type> error in Golang

In Golang, the cannot use <variable> (type <type>) as type <new-type> error occurs when a variable of one type is assigned or passed to a variable, parameter, or function that expects a different type. This error usually indicates a type mismatch between the variable and the expected type.

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

Example

package main

import "fmt"

func main() {
    var num float64 = 1.5
    var integer int = num
    fmt.Println(integer)
}

In this program, we declare a variable num of type float64 and initialize it with the value 1.5. We then declare another variable integer of type int and try to assign the value of num to integer. The fmt.Println() function is then used to print the value of integer to the console.

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

Output

./main.go:7:14: cannot use num (type float64) as type int in assignment

This error occurs because we are trying to assign a float64 value to an int variable. To fix this error, we need to explicitly convert the num variable to an int value using the int() function, like this:


Example

package main

import "fmt"

func main() {
    var num float64 = 1.5
    var integer int = int(num)
    fmt.Println(integer)
}

In this modified program, we use the int() function to convert the num variable to an int value before assigning it to the integer variable. This code will compile and run without any errors.

In summary, the "cannot use <variable> (type <type>) as type <new-type>" error in Golang occurs when a variable of one type is assigned or passed to a variable, parameter, or function that expects a different type. To fix this error, the developer needs to explicitly convert the variable to the expected type using type conversion functions or syntax.


Most Helpful This Week