dongxie3352 2017-08-10 07:45
浏览 66
已采纳

如何先声明struct然后再在switch语句中对其进行初始化?

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
  • 写回答

1条回答 默认 最新

  • dsbruqxgt820011351 2017-08-10 07:49
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘