Struct sugar

Summary

  • A sugar for struct syntax that allows named arguments and default values
  • Can be extended to enums, which allows overloading
  • Function call syntax reflects sugar to allow refactoring without breaking code

The sugar is valid when:

  • There is a single argument to a function, or, there is a single argument besides self in a method.
  • All members of a struct is public, or, function name is overloaded when taking enum.

Table overview:

|-------------|---------------------|----------------------------|
| Fn \ Syntax | Named               | Unnamed                    |
|-------------|---------------------|----------------------------|
| Unique name | struct/syntax       | struct/syntax              |
| Overloaded  | enum(struct)/syntax | enum/enum(struct)/syntax   |
  • A colon pub: struct makes all members in struct public
  • Desugar x: 1, y into Foo { x: 1, y: y } when Foo is expected, at least one named argument is required
  • Add new trait trait Optional<T> { fn none() -> Self, fn some(T) -> Self, fn to_option(self) -> Option<T> } and implement it for Option
  • Desugar val into Optional::some(val) whenever val is T and U: Optional<T> is expected where T and U do not match
  • Fill in with Optional::none() annotated x, .. with no following value
  • Desugar foo(bar: T = expr) { ... } into foo(bar: T) { let bar = match bar.to_option() { None => { expr } Some(val) => val } }; ...}
  • Desugar function argument and destructuring Foo { bar = expr } same as previous point
  • Type annotation becomes optional for destructure pattern in function argument, unless a generic or lifetime parameter is required
  • Enums used for overloading must have variants with unique parameter type signature
  • Desugar values into enum variants when function name is overloaded

Effects of this RFC:

  • Better ergonomics
  • Avoid line noise that do not represent a choice of performance
  • Cleaner syntax for unwrapping values from structs
  • Non-ambigious named syntax, overloading and defaults