-2

I would like to declare a struct first and then initialize it inside a switch statement. The code I've written so far shows declared and not used errors. However, I think the problem is different in my case and related to scope of declaration.

Could somebody please help me to make the below code work?

Car.go

package main

import "fmt"
import "strconv"

type Car struct{
    Name string
    Price int
}

func main(){
    name := "Fiat"
    car := &Car{}
    switch name {
        case "Fiat":
            car := &Car{
                Name : "Fiat",
                Price: 600000,
            }
        case "Mercedes-benz":
            car := &Car{
                Name : "Mercedes-benz",
                Price: 5600000,
            }
        default:
            car := &Car{
                Name : "Toyota",
                Price: 1000000,
            }

    }
    fmt.Println("Car Name : " + car.Name + " Price : " + strconv.Itoa(car.Price));
}

Errors

 $go run Car.go
./Car.go:19: car declared and not used
./Car.go:24: car declared and not used
./Car.go:29: car declared and not used
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
JSN
  • 2,035
  • 13
  • 27

1 Answers1

3

It's due to the scope of your variable declarations. You are shadowing the variable declaration inside the switch statement.

Simply change car:= to car= and you will be fine. You might also want to change car:=&Car{} to var car *Car. This will make your intent clearer and avoid an unnecessary allocation (as you are creating a new object which is never used).

Read about blocks & scopes and see the scoping section of the Go language reference.

Martin Campbell
  • 1,728
  • 10
  • 11