英文:
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 "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 )
}
}
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 := ""
b := ""
if i%3 == 0 {
a := "Fizz" // this creates a new "a", which shadows the outer "a" until the '}'
}
For assignment you want =
.
a:= ""
b:= ""
if i%3 == 0 {
a = "Fizz" // the original "a" is re-assigned
}
(ditto for b
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论