File: validation.rs

package info (click to toggle)
rust-derive-builder 0.20.1-2
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 500 kB
  • sloc: makefile: 2
file content (33 lines) | stat: -rw-r--r-- 900 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
//! This example illustrates the use of `validate` to add a pre-build validation
//! step.

use derive_builder::Builder;

#[derive(Builder, Debug, PartialEq)]
#[builder(build_fn(validate = Self::validate))]
struct Lorem {
    pub ipsum: u8,
}

impl LoremBuilder {
    /// Check that `Lorem` is putting in the right amount of effort.
    fn validate(&self) -> Result<(), String> {
        if let Some(ref ipsum) = self.ipsum {
            match *ipsum {
                i if i < 20 => Err("Try harder".to_string()),
                i if i > 100 => Err("You'll tire yourself out".to_string()),
                _ => Ok(()),
            }
        } else {
            Ok(())
        }
    }
}

fn main() {
    // If we're trying too hard...
    let x = LoremBuilder::default().ipsum(120).build().unwrap_err();

    // .. the build will fail:
    assert_eq!(&x.to_string(), "You'll tire yourself out");
}