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.

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

报告相同问题?

悬赏问题

  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题