4 ms·
I'm not an expert in Go, but can't you inline a statement before the conditional? value, err := bar(); err { // there was an error } I like how that l
by plexicle 11y ago
I'm not an expert in Go, but can't you inline a statement before the conditional?
value, err := bar(); err {
// there was an error
}
I like how that looks, personally. Obviously YMMV.
- kornish 11y agoIt does look better, but `value` will only be accessible inside the block. That's a no-go if you want to perform actions with `value` below.
- lobster_johnson 11y agoActually, that wasn't really the point of my paste. But since you ask: Nearly. You can do this: if value, err := bar(); err != nil { return err } Note that this syntax declares "value" in the "if" scope. You can only access it inside the "then" block or in an "else" block: if value, err := bar(); err != nil { return err } else { log.Print(value) // this compiles } log.Print(value) // does not compile So if you need it later, you have to do: var value MyType var err error if value, err = bar(); err != nil { return err } Note that you cannot do this: var value MyType if value, err := bar(); err != nil { return err } This would, again, declare a new "value" that shadows the outer "value" inside the "if" scope. (Go would fail to compile it since it doesn't allow unused variables.)