# Struct-syntax

**URL:** <https://internals.rust-lang.org/t/struct-syntax/15218>\
**Category:** language design\
**Created:** [August 23, 2021, 11:34pm UTC](https://internals.rust-lang.org/t/struct-syntax/15218 "2021-08-23T23:34:04Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![alonely0](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/alonely0/32/9632_2.png) [@alonely0](https://internals.rust-lang.org/u/alonely0)\
**Post date:** [August 23, 2021, 11:34pm UTC](https://internals.rust-lang.org/t/struct-syntax/15218/1 "2021-08-23T23:34:04Z")

</div>

This is inspired by `box syntax`. My idea is creating a kind of trait that, when implemented, lets you call a `T::new()`-like function with just writing a name that identifies the structure.

This makes easier creating structs that just need one value for being created.

For example:

```rust
#[derive(Debug)]
struct MyStruct {
    field_1: i64,
    field_2: i64,
}

impl MyStruct {
    pub fn new(x: i64) -> Self {
        Self { field_1: x, field_2: x * 3 }
    }
}

impl StructSyntax<i64> for MyStruct {
    const initializer: (&'static str, fn(i64) -> Self) = ("my_struct", Self::new);
}

fn main() {
    println!("{:?}", my_struct 1 /* the same as MyStruct::new(1) */);
}

// this would be somewhere in `core`
trait StructSyntax<T> {
    const initializer: (&'static str, fn(T) -> Self);
}

```

This way of implementing the idea is a backwards-compatible change because `T::new` still exists and is just called under the hood.

Also, it will make it easier and more simple to create boxes (making `box syntax` obsolete), and will be more coherent by creating in the same way `Rc`s, `Arc`s, and that stuff.

---

<div class="post-metadata">

**Author:** ![steffahn](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/steffahn/32/13288_2.png) [@steffahn](https://internals.rust-lang.org/u/steffahn)\
**Post date:** [August 23, 2021, 11:52pm UTC](https://internals.rust-lang.org/t/struct-syntax/15218/2 "2021-08-23T23:52:22Z")

</div>

[`box_syntax`](https://doc.rust-lang.org/beta/unstable-book/language-features/box-syntax.html) is unstable and [its tracking issue](https://github.com/rust-lang/rust/issues/49733) mostly features discussion on how (and when) to remove the feature from the language entirely (as well as discussion about placement new). I think most people are happy with using `T::new` functions. Thus, AFAICT, the chance of getting your idea / proposal into the language is vanishingly small.

---

<div class="post-metadata">

**Author:** ![mathstuf](https://avatars.discourse-cdn.com/v4/letter/m/958977/32.png) [@mathstuf](https://internals.rust-lang.org/u/mathstuf)\
**Post date:** [August 24, 2021, 12:01am UTC](https://internals.rust-lang.org/t/struct-syntax/15218/3 "2021-08-24T00:01:51Z")

</div>

I agree that this would need a _high_ bar to change. Importing a module which makes some variable names unusable?

```rust
let box = 1; // Not allowed because of `box` syntax
let my_struct = 1; // Not allowed just because I imported your module? No thank you.

```

This also has big knock-on effects for things like `rustfmt` (it now needs to resolve `use` references, look for `impl StructSyntax`, read the implementation, and then inject that into its formatter), `rust-analyzer` (though it has the infrastructure), or any other Rust-reading code for that matter. They'd all need to basically compile the code to even make an AST (which may require cross-compilation or something).

Another issue:

```rust
#[cfg(feature = "foobar")]
use module_which_declares_syntax;

#[cfg(feature = "foobar")]
fn foo() {
    let x = my_struct 1; // How do we make an AST of this when the `foobar` feature is off?
}

```

Sorry, but I feel that this is a bridge too far.

---

<div class="post-metadata">

**Author:** ![alonely0](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/alonely0/32/9632_2.png) [@alonely0](https://internals.rust-lang.org/u/alonely0)\
**Post date:** [August 24, 2021, 12:06am UTC](https://internals.rust-lang.org/t/struct-syntax/15218/4 "2021-08-24T00:06:03Z")

</div>

i think that the syntax should only be loaded only if the struct is in scope, not if you just import a module that has one inside.

---

<div class="post-metadata">

**Author:** ![ExpHP](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/exphp/32/6208_2.png) [@ExpHP](https://internals.rust-lang.org/u/ExpHP)\
**Post date:** [August 24, 2021, 12:39am UTC](https://internals.rust-lang.org/t/struct-syntax/15218/5 "2021-08-24T00:39:59Z")

</div>

> [@mathstuf](#):
>
> They'd all need to basically compile the code to even make an AST (which may require cross-compilation or something).

A better example:

```rust
let x = my_struct (3, 4); // create MyStruct with an (i32, i32)
let y = some_function(3, 4); // function call with two arguments

```

Basically the only way to make this even feasible is if you said, "well, `my_struct (3, 4)` can't be allowed then, it has to be `my_struct ((3, 4))`." Or, the compiler's internal representation has to model it as some sort of `MightBeFunctionCallOrStruct` until enough of the type system has been resolved to disambiguate between the two.

(imagine how awkward this would be if we had named arguments!)

> [@alonely0](#):
>
> i think that the syntax should only be loaded only if the struct is in scope, not if you just import a module that has one inside.

You are basically attempting to let users assign a new lexical class to certain identifiers, which is the same problem that makes C [famously difficult to parse](https://en.wikipedia.org/wiki/Lexer_hack). Only, in rust it would be _far far worse_ because we have to deal with path resolution, type inference and trait solving.

---

<div class="post-metadata">

**Author:** ![kornel](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/kornel/32/2711_2.png) [@kornel](https://internals.rust-lang.org/u/kornel)\
**Post date:** [August 24, 2021, 12:40am UTC](https://internals.rust-lang.org/t/struct-syntax/15218/6 "2021-08-24T00:40:55Z")

</div>

I actually like that Rust doesn't have any special syntax for constructors. This makes `new()` just a regular function. I can use `new() -> Result<Self>`, or `new_with_foo(Foo)`, and it's still the same regular syntax.

If syntax sugar for bare `new` existed, there would be immediately a feature request for overloading to support `my_struct foo` and `my_struct (bar, baz)`, and overloading by return type for `my_struct ?` and `my_struct .await`, etc. just to avoid losing the special favorited syntax because an object can be constructed in a few ways or asynchronously, etc.

---

<div class="post-metadata">

**Author:** ![mathstuf](https://avatars.discourse-cdn.com/v4/letter/m/958977/32.png) [@mathstuf](https://internals.rust-lang.org/u/mathstuf)\
**Post date:** [August 24, 2021, 12:50am UTC](https://internals.rust-lang.org/t/struct-syntax/15218/7 "2021-08-24T00:50:44Z")

</div>

> [@alonely0](#):
>
> i think that the syntax should only be loaded only if the struct is in scope, not if you just import a module that has one inside.

That is even more complicated for `rustfmt` because now it needs to know `use` statements _everywhere_, know what symbols are introduced by each, then know whether there's a `StructSyntax` in force in that scope.

> [@ExpHP](#):
>
> ```rust
> let x = my_struct (3, 4); // create MyStruct with an (i32, i32)
> let y = some_function(3, 4); // function call with two arguments
> 
> ```

Indeed. This is also problematic.

Other fun things that come to mind for `StructSyntax<T>::initializer.0` are listed below. Who errors for these things?

- `let`
- `{}` (or other syntactic soup)
- "🙂"
- `<right-to-left>` control character
- `\n`
- `;`

This is obviously not "just" a `&'static str`, but it has some other restrictions applied to it. It really feels like a new _literal_ that we don't even have today.

---

<div class="post-metadata">

**Author:** ![scottmcm](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/scottmcm/32/2355_2.png) [@scottmcm](https://internals.rust-lang.org/u/scottmcm)\
**Post date:** [August 24, 2021, 2:47am UTC](https://internals.rust-lang.org/t/struct-syntax/15218/8 "2021-08-24T02:47:48Z")

</div>

> [@alonely0](#):
>
> lets you call a `T::new()` -like function with just writing a name that identifies the structure.

FYI, you can already do [this](https://play.rust-lang.org/?edition=2018&gist=ff90dd7c311137f61c60ceb733a6cf5f), if you want:

```rust
#[derive(Debug)]
struct MyStruct {
    field_1: i64,
    field_2: i64,
}

#[allow(non_snake_case)]
fn MyStruct(x: i64) -> MyStruct {
    MyStruct {
        field_1: x,
        field_2: x * 3,
    }
}

fn main() {
    println!("{:?}", MyStruct(1));
}

```

(That's what tuple-structs do under the covers.)

---

<div class="post-metadata">

**Author:** ![steffahn](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/steffahn/32/13288_2.png) [@steffahn](https://internals.rust-lang.org/u/steffahn)\
**Post date:** [August 24, 2021, 9:39am UTC](https://internals.rust-lang.org/t/struct-syntax/15218/9 "2021-08-24T09:39:57Z")

</div>

We need to be explicit that while this is possible, it is entirely unidiomatic. It’s even worse than OPs suggestion which at least featured the name being in snake\_case. Seeing a PascalCase function call like this makes be believe it’s a tuple-struct constructor, not executing arbitrary code; not breaking this convention is valuable in making Rust code easy to understand.

The _correct_ way to do something like this while completely staying within the realm of acceptable rust code would be to use a regularly-named freestanding function. [Sometimes this approach can even be completely idiomatic, e.g. [std does it sometimes (though arguably in these cases the struct is named after the function and not the other way)](https://doc.rust-lang.org/std/iter/index.html#functions)].

```rust
#[derive(Debug)]
struct MyStruct {
    field_1: i64,
    field_2: i64,
}

fn my_struct(x: i64) -> MyStruct {
    MyStruct {
        field_1: x,
        field_2: x * 3,
    }
}

fn main() {
    println!("{:?}", my_struct(1));
}

```

---

<div class="post-metadata">

**Author:** ![chrisd](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/chrisd/32/7232_2.png) [@chrisd](https://internals.rust-lang.org/u/chrisd)\
**Post date:** [August 24, 2021, 11:49am UTC](https://internals.rust-lang.org/t/struct-syntax/15218/10 "2021-08-24T11:49:58Z")

</div>

> [@steffahn](#):
>
> We need to explicit that while this is possible, it is entirely unidiomatic

Isn't it what tuple structs do?

---

<div class="post-metadata">

**Author:** ![steffahn](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/steffahn/32/13288_2.png) [@steffahn](https://internals.rust-lang.org/u/steffahn)\
**Post date:** [August 24, 2021, 12:02pm UTC](https://internals.rust-lang.org/t/struct-syntax/15218/11 "2021-08-24T12:02:14Z")

</div>

Tuple structs do this, kind-of, but the behavior is predictable (e. g. not implicitly allocating anything), and the constructor can be used in pattern matching, too.

---

<div class="post-metadata">

**Author:** ![scottmcm](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/scottmcm/32/2355_2.png) [@scottmcm](https://internals.rust-lang.org/u/scottmcm)\
**Post date:** [August 24, 2021, 6:19pm UTC](https://internals.rust-lang.org/t/struct-syntax/15218/12 "2021-08-24T18:19:03Z")

</div>

> [@steffahn](#):
>
> We need to be explicit that while this is possible, it is entirely unidiomatic.

I definitely wouldn't use it for something like a big database record, but there are places it's reasonable.

For example, I wouldn't complain about

```rust
struct Color { r: u8, g: u8, b: u8 }
fn Color(r: u8, g: u8, b: u8) -> Color { Color { r, g, b } }

```

where positional initialization is reasonable but you still want named fields.

---

<div class="post-metadata">

**Author:** ![burjui](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/burjui/32/4113_2.png) [@burjui](https://internals.rust-lang.org/u/burjui)\
**Post date:** [August 25, 2021, 3:35pm UTC](https://internals.rust-lang.org/t/struct-syntax/15218/13 "2021-08-25T15:35:06Z")

</div>

But then the only difference is the absence of `::new`, which might only have significant impact, if a significant portion of your code consists of struct construction. And even if that's the case, I see no reason to subvert expectations and use CamelCase for a free function.

---

<div class="post-metadata">

**Author:** ![rajatpundir](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/rajatpundir/32/8459_2.png) [@rajatpundir](https://internals.rust-lang.org/u/rajatpundir)\
**Post date:** [August 25, 2021, 4:16pm UTC](https://internals.rust-lang.org/t/struct-syntax/15218/14 "2021-08-25T16:16:27Z")

</div>

Proposed syntax looks similar to the way they create stuff on the Haskell side. I really liked Haskell's brackets-are-optional approach. Don't have much of an opinion on how this would go here. I believe that in general the less the brackets, colons, and semicolons, the fun the language is to experiment with and create mind bending stuff.

---

<div class="post-metadata">

**Author:** ![jdahlstrom](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/jdahlstrom/32/3351_2.png) [@jdahlstrom](https://internals.rust-lang.org/u/jdahlstrom)\
**Post date:** [August 25, 2021, 4:52pm UTC](https://internals.rust-lang.org/t/struct-syntax/15218/15 "2021-08-25T16:52:32Z")

</div>

I’ve done this, but always with a snake\_case name. So a `struct Color {…}` has a constructor shorthand `fn color(…)` etc.

---

<div class="post-metadata">

**Author:** ![steffahn](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/steffahn/32/13288_2.png) [@steffahn](https://internals.rust-lang.org/u/steffahn)\
**Post date:** [August 25, 2021, 5:02pm UTC](https://internals.rust-lang.org/t/struct-syntax/15218/16 "2021-08-25T17:02:27Z")

</div>

> [@rajatpundir](#):
>
> I really liked Haskell's brackets-are-optional approach.

That goes hand-in-hand with currying every function by default. I wouldn’t know how to do this otherwise. Haskell’s syntactic ability to avoid parentheses for function calls _also_ goes hand-in-hand with its laziness, so you don’t need any `() -> T` functions.

Without laziness and without currying, you _could_ directly adapt one thing: no need for parentheses for single-argument functions (but they’d be needed for multiple-argument or zero-argument). That’s a rather narrowly applicable syntax then and would probably be a weird quirk if introduced to Rust.

In other words, _technically_ all functions in Haskell are single-argument functions (and that’s why its syntax works great there), while Rust differentiates different numbers of arguments on the most basic language level.

---

<div class="post-metadata">

**Author:** ![rajatpundir](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/rajatpundir/32/8459_2.png) [@rajatpundir](https://internals.rust-lang.org/u/rajatpundir)\
**Post date:** [August 25, 2021, 5:28pm UTC](https://internals.rust-lang.org/t/struct-syntax/15218/17 "2021-08-25T17:28:00Z")

</div>

Yeah, the Haskell is too pure to be practical which Rust is. I think the action would probably happen on the Haskell side in future, where they create some more language extensions to copy rust's innovation of ownership/lifetimes. Currently they seem to be busy with trying to work around dependent types and absorb Agda. I also have some ideas that I would like to experiment around dependent types and narrowing, current versions of languages could do a lot if only they could understand predicates that they are working with well enough before going entering a scope.

---

<div class="post-metadata">

**Author:** ![atagunov](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/atagunov/32/5877_2.png) [@atagunov](https://internals.rust-lang.org/u/atagunov)\
**Post date:** [August 25, 2021, 7:46pm UTC](https://internals.rust-lang.org/t/struct-syntax/15218/18 "2021-08-25T19:46:01Z")

</div>

> [@rajatpundir](#):
>
> Proposed syntax looks similar to the way they create stuff on the Haskell side

I thought Haskell syntax was inspired by ML, so you should be able to find the desired lack of parenthesis also in SML and OCaml. I understand these were an inspiration for Rust. It appears ML style parenthesis-less syntax however had been rejected in favor of C/C++/Java inspired one.

I have to concede that for a Java guy OCaml looks pretty difficult to read, at least as you start dealing with it. This is even more true for Haskell of course.

---

<div class="post-metadata">

**Author:** ![idanarye](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/idanarye/32/3346_2.png) [@idanarye](https://internals.rust-lang.org/u/idanarye)\
**Post date:** [August 30, 2021, 1:14am UTC](https://internals.rust-lang.org/t/struct-syntax/15218/19 "2021-08-30T01:14:25Z")

</div>

The point of `box` syntax is to have `box` patterns. Otherwise it's just more syntax to support.

---

<div class="post-metadata">

**Author:** ![nacaclanga](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/nacaclanga/32/7461_2.png) [@nacaclanga](https://internals.rust-lang.org/u/nacaclanga)\
**Post date:** [August 30, 2021, 9:44am UTC](https://internals.rust-lang.org/t/struct-syntax/15218/20 "2021-08-30T09:44:41Z")

</div>

`box` syntax consists of two constructs: `box` expressions (Rust's equivalent to C++'s `new` expressions) and `box` patterns.

`box` expressions are currently (at least in theory) still more powerfull compared to `Box::new()`, as they could support inplace constructions and the direct construction of boxed unsized types.

However, we do have agregate expressions and the `::new()` method convention, so I aggree, that we don't need new syntax here.

[Next page](https://internals.rust-lang.org/t/struct-syntax/15218.md?page=2)
