英文:
If and else disturb the variable scop in golang
问题
我有以下的Go语言代码:
var cmd1 *exec.Cmd
msg = receive_cmd()
if strings.Contains(msg, "Log-In") {
cmd1 := exec.Command("echo", "Please log in")
} else {
if strings.Contains(msg, "SignUp") {
cmd1 := exec.Command("echo", "Please SignUp")
}
}
var out bytes.Buffer
var stderr bytes.Buffer
cmd1.Stdout = &out
cmd1.Stderr = &stderr
err1 := cmd1.Run()
if err1 != nil {
fmt.Println(fmt.Sprint(err1) + " ##:## " + stderr.String() + "#####" + out.String())
return
}
我期望如果接收到登录消息,则使用"Please log in"作为echo命令的参数;如果接收到SignUp消息,则使用"Please SignUp"作为参数。
当我尝试运行上述代码时,它显示"cmd1 declared but not used"的错误。我该如何解决这个错误?这个错误的原因是什么?我在Stack Overflow上查找了很多答案,但没有什么帮助。
英文:
I have following golang code:
var cmd1 *exec.Cmd
msg=receive_cmd();
if strings.Contains(msg, "Log-In") {
cmd1 := exec.Command("echo", "Please log in")
}
else {
if strings.Contains(msg, "SignUp") {
cmd1 := exec.Command("echo", "Please SignUp")
}
}
var out bytes.Buffer
var stderr bytes.Buffer
cmd1.Stdout = &out
cmd1.Stderr = &stderr
err1 := cmd1.Run()
if err1 != nil {
fmt.Println(fmt.Sprint(err1) + " ##:## " + stderr.String() + "#####" + out.String())
return
}
I expect echo command with "Please log in" if login msg is received and "Please SignUp" if the message is SignUp.
When i am trying above code it says cmd1 declared but not used.
how can i remove this error? whats the reason for the error?
i have gone though many stack overflow answer on this but nothing is helping.
答案1
得分: 1
如果字符串中包含"Log-In",则执行以下代码:
cmd1 = exec.Command("echo", "Please log in")
否则,如果字符串中包含"SignUp",则执行以下代码:
cmd1 = exec.Command("echo", "Please SignUp")
请确保使用=
而不是:=
来避免重新声明cmd1,并将else
与前面的}
放在同一行上。
英文:
if strings.Contains(msg, "Log-In") {
cmd1 = exec.Command("echo", "Please log in")
} else {
if strings.Contains(msg, "SignUp") {
cmd1 = exec.Command("echo", "Please SignUp")
}
}
You need to make sure not to redeclare cmd1 by using =
instead of :=
, in addition to keeping else
on the same line as the preceding }
.
答案2
得分: 0
Go使用块进行词法作用域。您正在使用短变量声明语法在每个if
块中声明一个新的cmd1
变量。使用=
将值赋给现有变量。
var cmd1 *exec.Cmd
msg = receive_cmd()
if strings.Contains(msg, "Log-In") {
cmd1 = exec.Command("echo", "Please log in")
} else if strings.Contains(msg, "SignUp") {
cmd1 = exec.Command("echo", "Please SignUp")
}
英文:
Go is lexically scoped using blocks. You're using the short variable declaration syntax to declare a new cmd1
variable in each if
block. Assign the value to the existing variable with =
var cmd1 *exec.Cmd
msg = receive_cmd()
if strings.Contains(msg, "Log-In") {
cmd1 = exec.Command("echo", "Please log in")
} else if strings.Contains(msg, "SignUp") {
cmd1 = exec.Command("echo", "Please SignUp")
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论