Go Programming Experience
Novice
Other Languages Experience
Java, Python, Kotlin, JS
Related Idea
- [ ] Has this idea, or one like it, been proposed before?
- [ ] Does this affect error handling?
- [ ] Is this about generics?
- [ ] Is this change backward compatible? Breaking the Go 1 compatibility guarantee is a large cost and requires a large benefit
Has this idea, or one like it, been proposed before?
No, but not 100% sure
Does this affect error handling?
No.
Is this about generics?
No.
Proposal
This is a backward-compatible proposal to allow branching statement like if or switch to be used as an expression to be used for assignments.
This should reduce verbosity of code while keeping the impact minimal. It can also be used by static analysis tools to find unhandled scenarios with iota transformations. Also, it would inadvertantly mean that go would have a ternary operator.
Consider the following code to find the maximum of two numbers:
package main
import "fmt"
func main() {
a := 1
b := 2
var max int
if a > b {
max = a
} else {
max = b
}
fmt.Printf("max: %d\n", max)
}
with an if expression, it can be simplified to:
package main
import "fmt"
func main() {
a := 1
b := 2
max := if a > b {
a
} else {
b
}
fmt.Printf("max: %d\n", max)
}
Some similar proposals would get an alternative syntax to be implemented: - https://github.com/golang/go/issues/37739
Language Spec Changes
No response
Informal Change
No response
Is this change backward compatible?
Mostly. Haven't though about the whole picture
Orthogonality: How does this change interact or overlap with existing features?
No response
Would this change make Go easier or harder to learn, and why?
It would reduce the verbosity of the code and add an existing language feature of Python and Kotlin.
Cost Description
No response
Changes to Go ToolChain
gofmt, gopls, vet.
Performance Costs
No response
Prototype
No response
Comment From: gabyhelp
Related Issues and Documentation
- proposal: Go 2: Inline switch statement #61091 (closed)
- proposal: Go 2: Short statement in switch #56115 (closed)
- proposal: Go 2: spec: conditional-assign (?=) for limited ternary operator functionality #31659 (closed)
- proposal: Go 2: expression scoped variables #46105 (closed)
- proposal: Go 2: support new form of switch statement during variable assignment which jumps to function-wide case blocks #65019
- proposal: all : ternary operators in golang #60502 (closed)
- proposal: Go 2: support switch expressions #36036 (closed)
- proposal: Go 2: #63556 (closed)
- proposal: Go 2: #62241 (closed)
- proposal: Go 2: #61084 (closed)
(Emoji vote if this was helpful or unhelpful; more detailed feedback welcome in this discussion.)
Comment From: seankhliao
Duplicate of #44022