New to GO, error with assignment inside condition

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

New to GO, error with assignment inside condition

问题

我发现以下代码中的a和b在条件语句中被赋值,但未被使用:

package main

import "fmt"

//FizzBuzz n = 100
// Multiple of 3 output Fizz
//Multiple of 5 output Buzz
//Multiple of 3 and 5, FizzBuzz
func main(){
  for i:=0; i<=100; i++{
    a:= ""
    b:= ""
    if i%3 == 0 {
      a:="Fizz"
    }
    if i%5 == 0{
      b:="Buzz"
    }
    
    fmt.Println("number ",i,": ", a , b )

  }
}

谢谢,

英文:

I get an error with the code below that a and b assigned within the conditions are unused:

    package main

import &quot;fmt&quot;

//FizzBuzz n = 100
// Multiple of 3 output Fizz
//Multiple of 5 output Buzz
//Multiple of 3 and 5, FizzBuzz
func main(){
  for i:=0; i&lt;=100; i++{
	a:= &quot;&quot;
	b:= &quot;&quot;
	if i%3 == 0 {
		a:=&quot;Fizz&quot;
	}
	if i%5 == 0{
		b:=&quot;Buzz&quot;
		
	}
	
		fmt.Println(&quot;number &quot;,i,&quot;: &quot;, a , b )

	}
}

Thanks,

答案1

得分: 2

:= 在当前作用域中创建一个新变量。

a := ""
b := ""
if i%3 == 0 {
    a := "Fizz"  // 这创建了一个新的 "a",它会遮蔽外部的 "a",直到遇到 '}'
}

如果要进行赋值操作,请使用 =

a := ""
b := ""
if i%3 == 0 {
    a = "Fizz"  // 原来的 "a" 被重新赋值
}

(对于 "b" 也是一样的)

英文:

:= creates a new variable in the current scope.

a := &quot;&quot;
b := &quot;&quot;
if i%3 == 0 {
    a := &quot;Fizz&quot;  // this creates a new &quot;a&quot;, which shadows the outer &quot;a&quot; until the &#39;}&#39;
}

For assignment you want =.

a:= &quot;&quot;
b:= &quot;&quot;
if i%3 == 0 {
    a = &quot;Fizz&quot;  // the original &quot;a&quot; is re-assigned
}

(ditto for b)

huangapple
  • 本文由 发表于 2021年6月20日 21:55:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/68056542.html
匿名

发表评论

匿名网友

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

确定