Assignment mismatch: 2 variable but returns three values?


(Hamxa) #1

Hey,

I am trying to create a program which opens a file, and if in the file a line starts “1” then it call it “func1” and if line starts with “2” then it calls “func2”, but for some reason, my case 1 is working fine but I am getting error for my case 2.

The error I am getting is .\main.go:34:15: assignment mismatch: 2 variables but Package.pack2 returns 3 values

Can someone plz help me with this:

package main

import (
“bufio”
//“fmt”
package “local/package”
“log”
“os”
)

func main() {
file, err := os.Open(“file path”)

if err != nil {
	log.Fatalf("failed opening file: %s", err)
}

scanner := bufio.NewScanner(file)
var 0 package.pack1 
var 1 package.pack2
var 2 package.pack2
var 3 package.pack2

for scanner.Scan() {
	line := scanner.Text()
	switch line[0] {
	case '1':
		{
			0, err = package.func1(line)
			log.Fatal("The file has 1", 0)
		}
	case '2':
		{
			1, err = package.func2(line)
			log.Fatal("The file has 2", 1)
		
			2, err = package.func2(line)
			log.Fatal("The file has 3", 2)

			3, err = package.func2(line)
			log.Fatal("The file has 2", 3)


		}
	}
}

file.Close()

(Jakob Borg) #2

Hi!

There are a lot of things odd about your program, to the extent that I think the error you quote might be the least of your problems. :slight_smile: Have you tried the Go tour to get a good grasp of the basics?

After that I’d recommend starting with a smaller program that does something of your desired problem but not all of it - perhaps open and close a file, and see that you get no errors. Once that works, read a line from it and print it. Once that works, grab the first character of that line. And so on, iterating on one subproblem at a time.


(Christophe Meessen) #3

You can’t name a variable with a number. The following is invalid Go:

var 0 package.pack1 
var 1 package.pack2
var 2 package.pack2
var 3 package.pack2

The compiler should already report an error with these ones.
Use this instead:

var v0 package.pack1 
var v1 package.pack2
var v2 package.pack2
var v3 package.pack2

Replace in your program every occurrence of 0 with v0, 1 with v1, etc.

The error message is very clear. func2() returns three values, and you assign the returned values of func2 to two variables. func2 expects three variables.


(Hamxa) #4

Hi Chris,

I changed the variable to character but I am still getting the same error. My program is working fine until Case 1, but I am making mistake somewhere in case 2.

Thank you,


(Liza) #5

The issue is this:

If you post the definition of func2 we can point out the specific location where this is happening, but it might be more useful for the long term to go through the Go tour as Jakob above suggests.