Reputation: 1624
I have written the following program while learning from a tutorial. This is about checking conditionals in go
.
However, it is throwing error as undefined message
. Please help.
// Check out various conditional operators
package main
import "fmt"
func condition(x int) string {
if x > 5 {
message := "x is greater than 5"
} else if x == 5 {
message := "x is equal to 5"
} else {
message := "x is less than 5"
}
return message // error on this line
}
func main() {
x := 10 - 5
msg := condition(x)
fmt.Println("%s", msg)
}
Output receiving is:
user$ go run conditionals.go
# command-line-arguments
./conditionals.go:15:9: undefined: message
Upvotes: 0
Views: 545
Reputation: 22027
message
is scoped in each of the if/else branches. You want it scoped at the function level:
func condition(x int) string {
var message string
if x > 5 {
message = "x is greater than 5"
} else if x == 5 {
message = "x is equal to 5"
} else {
message = "x is less than 5"
}
return message
}
Since you are returning this value, you can update the function signature to include the returned variable e.g.
func condition(x int) (m string) {
if x > 5 {
m = "x is greater than 5"
}
// ...
return // implicitly returns m value
}
Upvotes: 2
Reputation: 19250
The problem is you define message
within a scope (i.e., inside curly braces), and your return statement is outside of those brackets. A solution would be to define message
in the same scope as your return statement, and then redefine message
in each conditional clause.
package main
import "fmt"
func condition(x int) string {
message := ""
if x > 5 {
message = "x is greater than 5"
} else if x == 5 {
message = "x is equal to 5"
} else {
message = "x is less than 5"
}
return message
}
func main() {
x := 10 - 5
msg := condition(x)
fmt.Println(msg)
}
https://play.golang.org/p/z_8h0ISNKYO
Upvotes: 1