</bugz loading .

Assignment mismatch: 1 variable but function returns 2 values - golang

assignment mismatch: x variable but function returns y values

Attempting to assign a number of return values of a function to a different number of variables frequently results in this error.
In simple words, this error occurs when the number of variables ( that you want to assign return values of a function ) and the number of return values of the function are not equal.
Similar to multiple-value in single-value context error.

Let us understand this with an example.

Example

package main

import (
        "fmt"
        "strconv"
)

func main(){
        strx := "69"
        intx := strconv.Atoi(strx) // cause of the error
        fmt.Println(intx)
}

Output

assignment mismatch: 1 variable but strconv.Atoi returns 2 values

In the above example, the strconv.Atoi function returns two values ( an integer & an error ), but there is only one variable ( intx ) to collect the return values. This mismatch results in the error.

Solution of assignment mismatch error

In order to overcome the assignment mismatch error, ensure that the number of variables ( to collect the return values of a function ) and the number of return values of the function are equal.

Example

package main

import (
        "fmt"
        "strconv"
)

func main(){
        strx := "69"
        intx,err := strconv.Atoi(strx)

        if err != nil {
                panic(err)
        }

        fmt.Println(intx)
}

Output

69

Alternative Solution

If you want to ignore the other return values of the function, you can alternatively use the underscore (_) symbol instead of the names of the variables.

Example

package main

import (
        "fmt"
        "strconv"
)

func main(){
        strx := "69"
        intx,_ := strconv.Atoi(strx) // using "_" instead of "err"
        fmt.Println(intx)
}

Output

69

Although the above example works fine, when the strconv.Atoi function throws an error, this code will crash. So, mostly try to avoid this solution.