如何在switch语句中先声明结构体,然后再初始化它?

huangapple go评论78阅读模式
英文:

How to declare struct first and initiliaze it later in switch statement?

问题

我想先声明一个结构体,然后在switch语句中对其进行初始化。到目前为止,我编写的代码显示了[declared and not used]错误。然而,我认为问题在于我的情况不同,并且与声明的作用域有关。

有人可以帮我使下面的代码正常工作吗?

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));
}

错误信息

 $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
英文:

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

得分: 3

这是由于你变量声明的作用域问题。你在switch语句内部重复声明了变量。

只需将car:=改为car=,问题就会解决。你可能还想将car:=&Car{}改为var car *Car。这样可以更清晰地表达你的意图,并避免不必要的内存分配(因为你创建了一个从未使用的新对象)。

请阅读有关块和作用域的内容,并查看Go语言参考手册中的作用域部分。

英文:

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.

huangapple
  • 本文由 发表于 2017年8月10日 15:45:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/45607483.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定