2

Example code, does not compile:

pub struct S {
    pub a: int,
    pub b: int
}

impl S {
    pub fn new(input: int) -> S {
        S { a: input + 1, b: a }
    }
}

The b: a bit isn't valid syntax, is there any way to do this in current Rust? [rustc 0.13.0-nightly (eedfc0779 2014-11-25 22:36:59 +0000)]

Obviously I could repeat input + 1 or use a temporary variable, but I'm curious specifically about using an already-initialized field as input to another field.

Nicholas Bishop
  • 1,141
  • 9
  • 21

1 Answers1

4

No, there is not anything for that, nor is it reasonable to expect that there ever will be; Rust’s ownership semantics would make it of very little value as it could only apply to Copy types well, references too.

The alternatives are so simple that complicating the language for such a feature is pretty much guaranteed not to happen.

Chris Morgan
  • 86,207
  • 24
  • 208
  • 215
  • The most useful form would be allowing earlier fields to appear in the initialisation of later fields (e.g. `S { a: input + 1, b: a.to_string() }`) and this certainly could work with non-`Copy` types. – huon Nov 27 '14 at 12:51
  • True, I had somehow forgotten about references. – Chris Morgan Nov 27 '14 at 13:24
  • Calling functions/methods with a reference to the earlier field was indeed what I was really interested in, thanks @dbaupp. – Nicholas Bishop Nov 27 '14 at 14:31