| Crates.io | up_set |
| lib.rs | up_set |
| version | 0.1.0 |
| created_at | 2025-05-09 13:42:33.703186+00 |
| updated_at | 2025-05-09 13:42:33.703186+00 |
| description | Set values, or update them using a closure |
| homepage | |
| repository | |
| max_upload_size | |
| id | 1666992 |
| size | 14,970 |
A #![no_std], no dependencies crate which allows you to write functions that either set the value or update it using a closure.
use up_set::UpSet;
#[derive(Debug, Eq, PartialEq)]
struct Point {
x: u32,
y: u32,
}
// `M` is a generic marker to guide Rust's type inference
// system to choose the correct implementation of `UpSet`
// for either `u32` or `Fn(u32) -> u32`
impl Point {
fn x<M, U: UpSet<u32, M>>(mut self, x: U) -> Self {
self.x = x.up_set(self.x);
self
}
fn y<M, U: UpSet<u32, M>>(mut self, y: U) -> Self {
self.y = y.up_set(self.y);
self
}
}
assert_eq!(
Point { x: 10, y: 10 }.x(20).y(|y| y + 50),
Point {
// `x` was set to a specific value
x: 20,
// `width` was updated
y: 60,
}
);
assert_eq!(
Point { x: 10, y: 10 }.x(|x| x + 20).y(50),
Point {
// `x` was updated
x: 30,
// `y` was set to a specific value
y: 50,
}
);
The benefit of this approach over using a pub field is that you can chain many updates together:
Rectangle {
x: 55,
y: 40,
height: 100,
width: 100,
}
.x(40)
.y(|y| y + 35)
.width(100)
.height(|h| h - 20)