Closed
Description
I propose the addition of an on
statement. Much like the if
statement, the block of the on
statement executes when the <expression>
is evaluated to true:
package main
import (
"log"
"os"
)
func main() {
stat, err := os.Stat("path/to/file.go")
on err != nil {
log.Fatal(err)
}
}
However, unlike the if
statement, the block of the on
statement executes whenever the <expression>
evaluates to true:
package main
import (
"fmt"
"log"
"os"
)
func main() {
var err error
on err != nil {
log.Fatal(err)
}
_, err = os.Stat("path/to/file.go")
_, err = os.Open("path/to/file.go")
}
Those two examples are using error handling because it's a controversial topic right now, but having an on
statement is more than just avoiding boilerplate code – in essence, the on
statement would improve the language expressiveness in my opinion. The example above shows another applicability:
package main
import (
"fmt"
"log"
)
type Response struct {
Close bool
Error error
Data string
}
func get(url string) *Response {
// Oversimplified code for the sake of example.
return &Response{
Close: true,
Error: nil,
Data: "",
}
}
func main() {
resp := get("https://github.com/golang/go/issues/33266")
on resp.Close {
fmt.Println("data received:", resp.Data)
}
on resp.Error != nil {
log.Fatal(resp.Error)
}
}
Thanks in advance.