Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: mention struct update syntax #37

Merged
merged 6 commits into from
Mar 19, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions src/language/custom-types/members.md
Original file line number Diff line number Diff line change
Expand Up @@ -309,10 +309,11 @@ Console.WriteLine(pt.ToString()); // prints: Point { X = 789, Y = 456 }
readonly record struct Point(int X, int Y);
```

There is no `with` in Rust, but to emulate something similar in Rust, it has
to be baked into the type's design:
There is no `with` in Rust, but the struct update syntax can be used
similar. This moves the original value, however:

```rust
#[derive(Debug)]
struct Point { x: i32, y: i32 }

impl Point {
Expand All @@ -322,10 +323,11 @@ impl Point {

pub fn x(&self) -> i32 { self.x }
pub fn y(&self) -> i32 { self.y }
}

// following methods consume self and return a new instance

pub fn set_x(self, val: i32) -> Self { Self::new(val, self.y) }
pub fn set_y(self, val: i32) -> Self { Self::new(self.x, val) }
fn main() {
let pt = Point::new(123, 456);
let pt = Point { x: 789, ..pt };
println!("{pt:?}"); // prints: Point { x: 789, y: 456 }
}
```