Option structs have become a de-facto standard mechanism of handling complex parameters for functions, it would be nice to be able to write statically typed key words arguments as an alternative to this binding structs-per-function. This would help de-clutter large code-bases where at least local conventions have been writing...
type HouseOptions struct {
Material string
HasFireplace bool
Composable bool
Floors int
}
func NewHouse(opts HouseOptions) *House {
// blah
}
Instead we could have
func NewHouse(opts: {Material: string, HasFireplace: bool, Composable: bool, Floors: int}) *House {
// blah
}
Saving six lines (even if the compiler compiles a Struct out of it).
Something like this already exists, but it might need to be slightly changed. I propose this:
func NewHouse(opts struct{Material string, HasFireplace bool, Composable bool, Floors int}) *House
The usage for that would be:
NewHouse(struct{
Material: "stuff",
})
Worth pointing out that this is similar to Zig's anonymous struct literals API:
dump(.{
.int = @as(u32, 1234),
.float = @as(f64, 12.34),
.b = true,
.s = "hi",
})
Possible dup of #12854
You can already do this, but the syntax for calling the function is not so nice:
https://play.golang.org/p/LzJxchVbWJn
package main
import (
"fmt"
)
func Foo(p struct { I int ; S string ; }) {
fmt.Printf("%d %s \n", p.I, p.S)
}
func main() {
fmt.Println("Hello, playground")
Foo(struct { I int ; S string ; }{7, "Foo"})
}
Great issue!
As discussed above, this seems similar to other proposals involving structs and composite literals. In particular, type inference on structs would seem to permit this, while also permitting other things as well.
Emoji voting for this proposal is not in favor.
For these reasons, this particular proposal is a likely decline. Leaving open for four weeks for final comments.
-- for @golang/proposal-review
No further comments.
Most helpful comment
Possible dup of #12854