How can I change the variable inside the if statement of switch statement in Golang?

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

How can I change the variable inside the if statement of switch statement in Golang?

问题

我是一个Golang的新手,现在我有一个要求,需要在if语句中更改一个值。

这是我的示例代码:

package main

func main() {
    a := "hi"
    pull_enable := true
    switch a {
    case "hi":
        image_list := []float32{
            0,
            2,
        }
        for image := 0; image < len(image_list); image++ {
            if image == 0 {
                pull_enable = true
                break
            }
        }
    }
}

我在switch语句外定义了一个变量pull_enable,我想在if语句中更改这个变量的值,但是当我构建它时,遇到了以下问题:

# command-line-arguments
pull_enable declared but not used

我想知道如何解决这个问题。有什么想法吗?

英文:

I am a newbie in Golang and now I have a requirement to change a value inside the if statement.

Here is my dummy code.

package main
func main() {    	
	a := &quot;hi&quot;
	pull_enable := true 
	switch a {
		case &quot;hi&quot;:
		image_list := []float32{
			0,				
			2,
			}
		for image:=0; image&lt;len(image_list); image++{
			if image == 0 {
				pull_enable = true 
				break
			}
		}
	}
}

I define a variable pull_enable outside of switch statement, and I want to change this variable value in the if statement, but when I built it, it encountered an issue below.

# command-line-arguments
pull_enable declared but not used

I am wondering how I can fix this issue. Is there any idea?

答案1

得分: 1


package main

import "fmt"

func main() {
	a := "hi"
	pullEnable := true
	switch a {
	case "hi":
		image_list := []float32{
			0,
			2,
		}
		for image := 0; image < len(image_list); image++ {
			if image == 0 {
				pullEnable = true
				break
			}
		}
	}
	fmt.Println(pullEnable)
}

这是你提供的代码的中文翻译。

英文:

package main

import &quot;fmt&quot;

func main() {
	a := &quot;hi&quot;
	pullEnable := true
	switch a {
	case &quot;hi&quot;:
		image_list := []float32{
			0,
			2,
		}
		for image := 0; image &lt; len(image_list); image++ {
			if image == 0 {
				pullEnable = true
				break
			}
		}
	}
	fmt.Println(pullEnable)
}

huangapple
  • 本文由 发表于 2022年8月31日 16:43:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/73553166.html
匿名

发表评论

匿名网友

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

确定