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.
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")
}
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 }
.