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.

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

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向