1 | //! Derive a builder for a struct |
2 | //! |
3 | //! This crate implements the [builder pattern] for you. |
4 | //! Just apply `#[derive(Builder)]` to a struct `Foo`, and it will derive an additional |
5 | //! struct `FooBuilder` with **setter**-methods for all fields and a **build**-method |
6 | //! — the way you want it. |
7 | //! |
8 | //! # Quick Start |
9 | //! |
10 | //! Add `derive_builder` as a dependency to you `Cargo.toml`. |
11 | //! |
12 | //! ## What you write |
13 | //! |
14 | //! ```rust |
15 | //! use derive_builder::Builder; |
16 | //! |
17 | //! #[derive(Builder)] |
18 | //! struct Lorem { |
19 | //! ipsum: u32, |
20 | //! // .. |
21 | //! } |
22 | //! # fn main() {} |
23 | //! ``` |
24 | //! |
25 | //! ## What you get |
26 | //! |
27 | //! ```rust |
28 | //! # use derive_builder::{Builder, UninitializedFieldError}; |
29 | //! # |
30 | //! # struct Lorem { |
31 | //! # ipsum: u32, |
32 | //! # } |
33 | //! # fn main() {} |
34 | //! # |
35 | //! #[derive(Clone, Default)] |
36 | //! struct LoremBuilder { |
37 | //! ipsum: Option<u32>, |
38 | //! } |
39 | //! # // bodge for testing: |
40 | //! # type LoremBuilderError = UninitializedFieldError; |
41 | //! |
42 | //! #[allow(dead_code)] |
43 | //! impl LoremBuilder { |
44 | //! pub fn ipsum(&mut self, value: u32) -> &mut Self { |
45 | //! let mut new = self; |
46 | //! new.ipsum = Some(value); |
47 | //! new |
48 | //! } |
49 | //! |
50 | //! fn build(&self) -> Result<Lorem, LoremBuilderError> { |
51 | //! Ok(Lorem { |
52 | //! ipsum: Clone::clone(self.ipsum |
53 | //! .as_ref() |
54 | //! .ok_or(LoremBuilderError::from(UninitializedFieldError::new("ipsum" )))?), |
55 | //! }) |
56 | //! } |
57 | //! } |
58 | //! ``` |
59 | //! |
60 | //! By default all generated setter-methods take and return `&mut self` |
61 | //! (aka _non-consuming_ builder pattern). Accordingly, the build method also takes a |
62 | //! reference by default. |
63 | //! |
64 | //! You can easily opt into different patterns and control many other aspects. |
65 | //! |
66 | //! The build method returns `Result<T, E>`, where `T` is the struct you started with |
67 | //! and E is a generated builder error type. |
68 | //! It returns `Err` if you didn't initialize all fields and no default values were |
69 | //! provided. |
70 | //! |
71 | //! # Builder Patterns |
72 | //! |
73 | //! Let's look again at the example above. You can now build structs like this: |
74 | //! |
75 | //! ```rust |
76 | //! # use derive_builder::Builder; |
77 | //! # #[derive(Builder)] struct Lorem { ipsum: u32 } |
78 | //! # fn try_main() -> Result<(), Box<dyn std::error::Error>> { |
79 | //! let x: Lorem = LoremBuilder::default().ipsum(42).build()?; |
80 | //! # Ok(()) |
81 | //! # } fn main() { try_main().unwrap(); } |
82 | //! ``` |
83 | //! |
84 | //! Ok, _chaining_ method calls is nice, but what if `ipsum(42)` should only happen if `geek = true`? |
85 | //! |
86 | //! So let's make this call conditional |
87 | //! |
88 | //! ```rust |
89 | //! # use derive_builder::Builder; |
90 | //! # #[derive(Builder)] struct Lorem { ipsum: u32 } |
91 | //! # fn try_main() -> Result<(), Box<dyn std::error::Error>> { |
92 | //! # let geek = true; |
93 | //! let mut builder = LoremBuilder::default(); |
94 | //! if geek { |
95 | //! builder.ipsum(42); |
96 | //! } |
97 | //! let x: Lorem = builder.build()?; |
98 | //! # Ok(()) |
99 | //! # } fn main() { try_main().unwrap(); } |
100 | //! ``` |
101 | //! |
102 | //! Now it comes in handy that our setter methods take and return mutable references. Otherwise |
103 | //! we would need to write something more clumsy like `builder = builder.ipsum(42)` to reassign |
104 | //! the return value each time we have to call a setter conditionally. |
105 | //! |
106 | //! Setters with mutable references are therefore a convenient default for the builder |
107 | //! pattern in Rust. |
108 | //! |
109 | //! But this is a free world and the choice is still yours! |
110 | //! |
111 | //! ## Owned, aka Consuming |
112 | //! |
113 | //! Precede your struct (or field) with `#[builder(pattern = "owned")]` to opt into this pattern. |
114 | //! Builders generated with this pattern do not automatically derive `Clone`, which allows builders |
115 | //! to be generated for structs with fields that do not derive `Clone`. |
116 | //! |
117 | //! * Setters take and return `self`. |
118 | //! * PRO: Setter calls and final build method can be chained. |
119 | //! * CON: If you don't chain your calls, you have to create a reference to each return value, |
120 | //! e.g. `builder = builder.ipsum(42)`. |
121 | //! |
122 | //! ## Mutable, aka Non-Consuming (recommended) |
123 | //! |
124 | //! This pattern is recommended and active by default if you don't specify anything else. |
125 | //! You can precede your struct (or field) with `#[builder(pattern = "mutable")]` |
126 | //! to make this choice explicit. |
127 | //! |
128 | //! * Setters take and return `&mut self`. |
129 | //! * PRO: Setter calls and final build method can be chained. |
130 | //! * CON: The build method must clone or copy data to create something owned out of a |
131 | //! mutable reference. Otherwise it could not be used in a chain. **(*)** |
132 | //! |
133 | //! ## Immutable |
134 | //! |
135 | //! Precede your struct (or field) with `#[builder(pattern = "immutable")]` to opt into this pattern. |
136 | //! |
137 | //! * Setters take and return `&self`. |
138 | //! * PRO: Setter calls and final build method can be chained. |
139 | //! * CON: If you don't chain your calls, you have to create a reference to each return value, |
140 | //! e.g. `builder = builder.ipsum(42)`. |
141 | //! * CON: The build method _and each setter_ must clone or copy data to create something owned |
142 | //! out of a reference. **(*)** |
143 | //! |
144 | //! ## (*) Performance Considerations |
145 | //! |
146 | //! Luckily Rust is clever enough to optimize these clone-calls away in release builds |
147 | //! for your every-day use cases. Thats quite a safe bet - we checked this for you. ;-) |
148 | //! Switching to consuming signatures (=`self`) is unlikely to give you any performance |
149 | //! gain, but very likely to restrict your API for non-chained use cases. |
150 | //! |
151 | //! # More Features |
152 | //! |
153 | //! ## Hidden Fields |
154 | //! |
155 | //! You can hide fields by skipping their setters on (and presence in) the builder struct. |
156 | //! |
157 | //! - Opt-out — skip setters via `#[builder(setter(skip))]` on individual fields. |
158 | //! - Opt-in — set `#[builder(setter(skip))]` on the whole struct |
159 | //! and enable individual setters via `#[builder(setter)]`. |
160 | //! |
161 | //! The types of skipped fields must implement `Default`. |
162 | //! |
163 | //! ```rust |
164 | //! # use derive_builder::Builder; |
165 | //! # |
166 | //! #[derive(Builder)] |
167 | //! struct HiddenField { |
168 | //! setter_present: u32, |
169 | //! #[builder(setter(skip))] |
170 | //! setter_skipped: u32, |
171 | //! } |
172 | //! # fn main() {} |
173 | //! ``` |
174 | //! |
175 | //! Alternatively, you can use the more verbose form: |
176 | //! |
177 | //! - `#[builder(setter(skip = true))]` |
178 | //! - `#[builder(setter(skip = false))]` |
179 | //! |
180 | //! ## Custom setters (skip autogenerated setters) |
181 | //! |
182 | //! Similarly to `setter(skip)`, you can say that you will provide your own setter methods. |
183 | //! This simply suppresses the generation of the setter, leaving the field in the builder, |
184 | //! as `Option<T>`. |
185 | //! |
186 | //! ```rust |
187 | //! # use derive_builder::Builder; |
188 | //! # |
189 | //! #[derive(Builder)] |
190 | //! struct SetterOptOut { |
191 | //! #[builder(setter(custom))] |
192 | //! custom_setter: u32, |
193 | //! } |
194 | //! impl SetterOptOutBuilder { |
195 | //! fn custom_setter(&mut self, value: u32) { |
196 | //! self.custom_setter = Some(value); |
197 | //! } |
198 | //! } |
199 | //! # fn main() {} |
200 | //! ``` |
201 | //! |
202 | //! Again, the more verbose form is accepted: |
203 | //! |
204 | //! - `#[builder(setter(custom = true))]` |
205 | //! - `#[builder(setter(custom = false))]` |
206 | //! |
207 | //! ## Setter Visibility |
208 | //! |
209 | //! Setters are public by default. You can precede your struct (or field) with `#[builder(public)]` |
210 | //! to make this explicit. |
211 | //! |
212 | //! Otherwise precede your struct (or field) with `#[builder(private)]` to opt into private |
213 | //! setters. |
214 | //! |
215 | //! ## Generated builder struct name |
216 | //! |
217 | //! By default, the builder struct for `struct Foo` is `FooBuilder`. |
218 | //! You can override this: |
219 | //! |
220 | //! ```rust |
221 | //! # use derive_builder::Builder; |
222 | //! # |
223 | //! #[derive(Builder)] |
224 | //! #[builder(name = "FooConstructor" )] |
225 | //! struct Foo { } |
226 | //! |
227 | //! # fn main() -> Result<(), FooConstructorError> { |
228 | //! let foo: Foo = FooConstructor::default().build()?; |
229 | //! # Ok(()) |
230 | //! # } |
231 | //! ``` |
232 | //! |
233 | //! ## Setter Name/Prefix |
234 | //! |
235 | //! Setter methods are named after their corresponding field by default. |
236 | //! |
237 | //! - You can customize the setter name via `#[builder(setter(name = "foo"))`. |
238 | //! - Alternatively you can set a prefix via `#[builder(setter(prefix = "xyz"))`, which will change |
239 | //! the method name to `xyz_foo` if the field is named `foo`. Note that an underscore is |
240 | //! inserted, since Rust favors snake case here. |
241 | //! |
242 | //! Prefixes can also be defined on the struct level, but renames only work on fields. Renames |
243 | //! take precedence over prefix definitions. |
244 | //! |
245 | //! ## Generic Setters |
246 | //! |
247 | //! You can make each setter generic over the `Into`-trait. It's as simple as adding |
248 | //! `#[builder(setter(into))]` to either a field or the whole struct. |
249 | //! |
250 | //! ```rust |
251 | //! # use derive_builder::Builder; |
252 | //! # |
253 | //! #[derive(Builder, Debug, PartialEq)] |
254 | //! struct Lorem { |
255 | //! #[builder(setter(into))] |
256 | //! pub ipsum: String, |
257 | //! } |
258 | //! |
259 | //! fn main() { |
260 | //! // `"foo"` will be converted into a `String` automatically. |
261 | //! let x = LoremBuilder::default().ipsum("foo" ).build().unwrap(); |
262 | //! |
263 | //! assert_eq!(x, Lorem { |
264 | //! ipsum: "foo" .to_string(), |
265 | //! }); |
266 | //! } |
267 | //! ``` |
268 | //! |
269 | //! ## Setters for Option |
270 | //! |
271 | //! You can avoid wrapping values in `Some(...)` for fields of type `Option<T>`. It's as simple as adding |
272 | //! `#[builder(setter(strip_option))]` to either a single field or the whole struct. |
273 | //! |
274 | //! ```rust |
275 | //! # use derive_builder::Builder; |
276 | //! # |
277 | //! #[derive(Builder, Debug, PartialEq)] |
278 | //! struct Lorem { |
279 | //! #[builder(setter(into, strip_option))] |
280 | //! pub ipsum: Option<String>, |
281 | //! #[builder(setter(into, strip_option), default)] |
282 | //! pub foo: Option<String>, |
283 | //! } |
284 | //! |
285 | //! fn main() { |
286 | //! // `"foo"` will be converted into a `String` automatically. |
287 | //! let x = LoremBuilder::default().ipsum("foo" ).build().unwrap(); |
288 | //! |
289 | //! assert_eq!(x, Lorem { |
290 | //! ipsum: Some("foo" .to_string()), |
291 | //! foo: None |
292 | //! }); |
293 | //! } |
294 | //! ``` |
295 | //! If you want to set the value to None when unset, then enable `default` on this field (or do not use `strip_option`). |
296 | //! |
297 | //! Limitation: only the `Option` type name is supported, not type alias nor `std::option::Option`. |
298 | //! |
299 | //! ## Fallible Setters |
300 | //! |
301 | //! Alongside the normal setter methods, you can expose fallible setters which are generic over |
302 | //! the `TryInto` trait. TryInto is similar to `Into` with the key distinction that the conversion |
303 | //! can fail, and therefore produces a `Result`. |
304 | //! |
305 | //! You can only declare the `try_setter` attribute today if you're targeting nightly, and you have |
306 | //! to add `#![feature(try_from)]` to your crate to use it. |
307 | //! |
308 | //! ```rust |
309 | //! # use derive_builder::Builder; |
310 | //! #[derive(Builder, Debug, PartialEq)] |
311 | //! #[builder(try_setter, setter(into))] |
312 | //! struct Lorem { |
313 | //! pub name: String, |
314 | //! pub ipsum: u8, |
315 | //! } |
316 | //! |
317 | //! #[derive(Builder, Debug, PartialEq)] |
318 | //! struct Ipsum { |
319 | //! #[builder(try_setter, setter(into, name = "foo" ))] |
320 | //! pub dolor: u8, |
321 | //! } |
322 | //! |
323 | //! fn main() { |
324 | //! LoremBuilder::default() |
325 | //! .try_ipsum(1u16).unwrap() |
326 | //! .name("hello" ) |
327 | //! .build() |
328 | //! .expect("1 fits into a u8" ); |
329 | //! |
330 | //! IpsumBuilder::default() |
331 | //! .try_foo(1u16).unwrap() |
332 | //! .build() |
333 | //! .expect("1 fits into a u8" ); |
334 | //! } |
335 | //! ``` |
336 | //! |
337 | //! ## Default Values |
338 | //! |
339 | //! You can define default values for each field via annotation by `#[builder(default = "...")]`, |
340 | //! where `...` stands for any Rust expression and must be string-escaped, e.g. |
341 | //! |
342 | //! * `#[builder(default = "42")]` |
343 | //! * `#[builder(default)]` delegates to the [`Default`] trait of the base type. |
344 | //! |
345 | //! The expression will be evaluated with each call to `build`. |
346 | //! |
347 | //! ```rust |
348 | //! # use derive_builder::Builder; |
349 | //! # |
350 | //! #[derive(Builder, Debug, PartialEq)] |
351 | //! struct Lorem { |
352 | //! #[builder(default = "42" )] |
353 | //! pub ipsum: u32, |
354 | //! } |
355 | //! |
356 | //! fn main() { |
357 | //! // If we don't set the field `ipsum`, |
358 | //! let x = LoremBuilder::default().build().unwrap(); |
359 | //! |
360 | //! // .. the custom default will be used for `ipsum`: |
361 | //! assert_eq!(x, Lorem { |
362 | //! ipsum: 42, |
363 | //! }); |
364 | //! } |
365 | //! ``` |
366 | //! |
367 | //! ### Tips on Defaults |
368 | //! |
369 | //! * The `#[builder(default)]` annotation can be used on the struct level, too. Overrides are |
370 | //! still possible. |
371 | //! * Delegate to a private helper method on `FooBuilder` for anything fancy. This way |
372 | //! you will get _much better error diagnostics_ from the rust compiler and it will be _much |
373 | //! more readable_ for other human beings. :-) |
374 | //! * Defaults will not work while using `#[builder(build_fn(skip))]`. In this case, you'll |
375 | //! need to handle default values yourself when converting from the builder, such as by |
376 | //! using `.unwrap_or()` and `.unwrap_or_else()`. |
377 | //! |
378 | //! [`Default`]: https://doc.rust-lang.org/std/default/trait.Default.html |
379 | //! |
380 | //! ```rust |
381 | //! # use derive_builder::Builder; |
382 | //! # |
383 | //! # #[derive(Builder, PartialEq, Debug)] |
384 | //! struct Lorem { |
385 | //! ipsum: String, |
386 | //! // Custom defaults can delegate to helper methods |
387 | //! // and pass errors to the enclosing `build()` method via `?`. |
388 | //! #[builder(default = "self.default_dolor()?" )] |
389 | //! dolor: String, |
390 | //! } |
391 | //! |
392 | //! impl LoremBuilder { |
393 | //! // Private helper method with access to the builder struct. |
394 | //! fn default_dolor(&self) -> Result<String, String> { |
395 | //! match self.ipsum { |
396 | //! Some(ref x) if x.chars().count() > 3 => Ok(format!("dolor {}" , x)), |
397 | //! _ => Err("ipsum must at least 3 chars to build dolor" .to_string()), |
398 | //! } |
399 | //! } |
400 | //! } |
401 | //! |
402 | //! # fn main() { |
403 | //! # let x = LoremBuilder::default() |
404 | //! # .ipsum("ipsum" .to_string()) |
405 | //! # .build() |
406 | //! # .unwrap(); |
407 | //! # |
408 | //! # assert_eq!(x, Lorem { |
409 | //! # ipsum: "ipsum" .to_string(), |
410 | //! # dolor: "dolor ipsum" .to_string(), |
411 | //! # }); |
412 | //! # } |
413 | //! ``` |
414 | //! |
415 | //! You can even reference other fields, but you have to remember that the builder struct |
416 | //! will wrap every type in an Option ([as illustrated earlier](#what-you-get)). |
417 | //! |
418 | //! ## Generic Structs |
419 | //! |
420 | //! ```rust |
421 | //! # use derive_builder::Builder; |
422 | //! # |
423 | //! #[derive(Builder, Debug, PartialEq, Default, Clone)] |
424 | //! struct GenLorem<T: Clone> { |
425 | //! ipsum: &'static str, |
426 | //! dolor: T, |
427 | //! } |
428 | //! |
429 | //! fn main() { |
430 | //! let x = GenLoremBuilder::default().ipsum("sit" ).dolor(42).build().unwrap(); |
431 | //! assert_eq!(x, GenLorem { ipsum: "sit" .into(), dolor: 42 }); |
432 | //! } |
433 | //! ``` |
434 | //! |
435 | //! ## Build Method Customization |
436 | //! |
437 | //! You can rename or suppress the auto-generated build method, leaving you free to implement |
438 | //! your own version. Suppression is done using `#[builder(build_fn(skip))]` at the struct level, |
439 | //! and renaming is done with `#[builder(build_fn(name = "YOUR_NAME"))]`. |
440 | //! |
441 | //! Additionally if you want to make the build method private you can apply `#[builder(build_fn(private))]`. |
442 | //! |
443 | //! ## Pre-Build Validation |
444 | //! |
445 | //! If you're using the provided `build` method, you can declare |
446 | //! `#[builder(build_fn(validate = "path::to::fn"))]` to specify a validator function which gets |
447 | //! access to the builder before construction. The path does not need to be fully-qualified, and |
448 | //! will consider `use` statements made at module level. It must be accessible from the scope |
449 | //! where the target struct is declared. |
450 | //! |
451 | //! The provided function must have the signature `(&FooBuilder) -> Result<_, String>`; |
452 | //! the `Ok` variant is not used by the `build` method. |
453 | //! |
454 | //! ```rust |
455 | //! # use derive_builder::Builder; |
456 | //! # |
457 | //! #[derive(Builder, Debug, PartialEq)] |
458 | //! #[builder(build_fn(validate = "Self::validate" ))] |
459 | //! struct Lorem { |
460 | //! pub ipsum: u8, |
461 | //! } |
462 | //! |
463 | //! impl LoremBuilder { |
464 | //! /// Check that `Lorem` is putting in the right amount of effort. |
465 | //! fn validate(&self) -> Result<(), String> { |
466 | //! if let Some(ref ipsum) = self.ipsum { |
467 | //! match *ipsum { |
468 | //! i if i < 20 => Err("Try harder" .to_string()), |
469 | //! i if i > 100 => Err("You'll tire yourself out" .to_string()), |
470 | //! _ => Ok(()) |
471 | //! } |
472 | //! } else { |
473 | //! Ok(()) |
474 | //! } |
475 | //! } |
476 | //! } |
477 | //! |
478 | //! fn main() { |
479 | //! // If we're trying too hard... |
480 | //! let x = LoremBuilder::default().ipsum(120).build().unwrap_err(); |
481 | //! |
482 | //! // .. the build will fail: |
483 | //! assert_eq!(&x.to_string(), "You'll tire yourself out" ); |
484 | //! } |
485 | //! ``` |
486 | //! |
487 | //! Note: |
488 | //! * Default values are applied _after_ validation, and will therefore not be validated! |
489 | //! |
490 | //! ## Additional Trait Derivations |
491 | //! |
492 | //! You can derive additional traits on the builder, including traits defined by other crates: |
493 | //! |
494 | //! ```rust |
495 | //! # use derive_builder::Builder; |
496 | //! # |
497 | //! #[derive(Builder, Clone)] |
498 | //! #[builder(derive(Debug, PartialEq, Eq))] |
499 | //! pub struct Lorem { |
500 | //! foo: u8, |
501 | //! bar: String, |
502 | //! } |
503 | //! |
504 | //! fn main() { |
505 | //! assert_eq!(LoremBuilder::default(), LoremBuilder::default()); |
506 | //! } |
507 | //! ``` |
508 | //! |
509 | //! Attributes declared for those traits are _not_ forwarded to the fields on the builder. |
510 | //! |
511 | //! ## Documentation Comments and Attributes |
512 | //! |
513 | //! `#[derive(Builder)]` copies doc comments and attributes (`#[...]`) from your fields |
514 | //! to the according builder fields and setter-methods, if it is one of the following: |
515 | //! |
516 | //! * `/// ...` |
517 | //! * `#[doc = ...]` |
518 | //! * `#[cfg(...)]` |
519 | //! * `#[allow(...)]` |
520 | //! |
521 | //! The whitelisting minimizes interference with other custom attributes like |
522 | //! those used by Serde, Diesel, or others. |
523 | //! |
524 | //! ```rust |
525 | //! # use derive_builder::Builder; |
526 | //! # |
527 | //! #[derive(Builder)] |
528 | //! struct Lorem { |
529 | //! /// `ipsum` may be any `String` (be creative). |
530 | //! ipsum: String, |
531 | //! #[doc = r"`dolor` is the estimated amount of work." ] |
532 | //! dolor: i32, |
533 | //! // `#[derive(Builder)]` understands conditional compilation via cfg-attributes, |
534 | //! // i.e. => "no field = no setter". |
535 | //! #[cfg (target_os = "macos" )] |
536 | //! #[allow (non_snake_case)] |
537 | //! Im_a_Mac: bool, |
538 | //! } |
539 | //! # fn main() {} |
540 | //! ``` |
541 | //! |
542 | //! ### Pass-through Attributes |
543 | //! |
544 | //! You can set attributes on elements of the builder using the `builder_*_attr` attributes: |
545 | //! |
546 | //! - `builder_struct_attr` adds attributes after `#[derive(...)]` on the builder struct. |
547 | //! - `builder_impl_attr` adds attributes on the `impl` block |
548 | //! - `builder_field_attr` adds attributes to field declarations in the builder struct. |
549 | //! - `builder_setter_attr` adds attributes to the setter in the `impl` block. |
550 | //! |
551 | //! ```rust |
552 | //! # use derive_builder::Builder; |
553 | //! # |
554 | //! #[derive(Builder)] |
555 | //! #[builder(derive(serde::Serialize))] |
556 | //! #[builder_struct_attr(serde(rename_all = "camelCase" ))] |
557 | //! struct Lorem { |
558 | //! #[builder_field_attr(serde(rename="dolor" ))] |
559 | //! ipsum: String, |
560 | //! } |
561 | //! |
562 | //! # fn main() { |
563 | //! let mut show = LoremBuilder::default(); |
564 | //! show.ipsum("sit" .into()); |
565 | //! assert_eq!(serde_json::to_string(&show).unwrap(), r#"{"dolor":"sit"}"# ); |
566 | //! # } |
567 | //! ``` |
568 | //! |
569 | //! # Error return type from autogenerated `build` function |
570 | //! |
571 | //! By default, `build` returns an autogenerated error type: |
572 | //! |
573 | //! ```rust |
574 | //! # use derive_builder::UninitializedFieldError; |
575 | //! # use std::fmt::{self, Display}; |
576 | //! # |
577 | //! #[doc="Error type for LoremBuilder" ] |
578 | //! #[derive(Debug)] |
579 | //! #[non_exhaustive] |
580 | //! pub enum LoremBuilderError { // where `LoremBuilder` is the name of the builder struct |
581 | //! /// Uninitialized field |
582 | //! UninitializedField(&'static str), |
583 | //! /// Custom validation error |
584 | //! ValidationError(String), |
585 | //! } |
586 | //! |
587 | //! impl From<String> for LoremBuilderError { |
588 | //! fn from(s: String) -> Self { Self::ValidationError(s) } |
589 | //! } |
590 | //! impl From<UninitializedFieldError> for LoremBuilderError { // ... |
591 | //! # fn from(s: UninitializedFieldError) -> Self { todo!() } } |
592 | //! impl Display for LoremBuilderError { // ... |
593 | //! # fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result { todo!() } } |
594 | //! impl std::error::Error for LoremBuilderError {} |
595 | //! ``` |
596 | //! |
597 | //! Alternatively, you can specify your own error type: |
598 | //! ```rust |
599 | //! # use derive_builder::{Builder, UninitializedFieldError}; |
600 | //! # |
601 | //! #[derive(Builder, Debug, PartialEq)] |
602 | //! #[builder(build_fn(error = "OurLoremError" ))] |
603 | //! struct Lorem { |
604 | //! pub ipsum: u32, |
605 | //! } |
606 | //! |
607 | //! struct OurLoremError(String); |
608 | //! |
609 | //! impl From<UninitializedFieldError> for OurLoremError { |
610 | //! fn from(ufe: UninitializedFieldError) -> OurLoremError { OurLoremError(ufe.to_string()) } |
611 | //! } |
612 | //! |
613 | //! # fn main() { |
614 | //! let err: OurLoremError = LoremBuilder::default().build().unwrap_err(); |
615 | //! assert_eq!(&err.0, "Field not initialized: ipsum" ); |
616 | //! # } |
617 | //! ``` |
618 | //! |
619 | //! # Completely custom fields in the builder |
620 | //! |
621 | //! Instead of having an `Option`, you can have whatever type you like: |
622 | //! |
623 | //! ```rust |
624 | //! # use derive_builder::Builder; |
625 | //! #[derive(Debug, PartialEq, Default, Builder, Clone)] |
626 | //! #[builder(derive(Debug, PartialEq))] |
627 | //! struct Lorem { |
628 | //! #[builder(setter(into), field(ty = "u32" ))] |
629 | //! ipsum: u32, |
630 | //! |
631 | //! #[builder(field(ty = "String" , build = "()" ))] |
632 | //! dolor: (), |
633 | //! |
634 | //! #[builder(field(ty = "&'static str" , build = "self.amet.parse()?" ))] |
635 | //! amet: u32, |
636 | //! } |
637 | //! |
638 | //! impl From<std::num::ParseIntError> for LoremBuilderError { // ... |
639 | //! # fn from(e: std::num::ParseIntError) -> LoremBuilderError { |
640 | //! # e.to_string().into() |
641 | //! # } |
642 | //! # } |
643 | //! |
644 | //! # fn main() { |
645 | //! let mut builder = LoremBuilder::default(); |
646 | //! builder.ipsum(42u16).dolor("sit" .into()).amet("12" ); |
647 | //! assert_eq!(builder, LoremBuilder { ipsum: 42, dolor: "sit" .into(), amet: "12" }); |
648 | //! let lorem = builder.build().unwrap(); |
649 | //! assert_eq!(lorem, Lorem { ipsum: 42, dolor: (), amet: 12 }); |
650 | //! # } |
651 | //! ``` |
652 | //! |
653 | //! The builder field type (`ty =`) must implement `Default`. |
654 | //! |
655 | //! The argument to `build` must be a literal string containing Rust code for the contents of a block, which must evaluate to the type of the target field. |
656 | //! It may refer to the builder struct as `self`, use `?`, etc. |
657 | //! |
658 | //! # **`#![no_std]`** Support (on Nightly) |
659 | //! |
660 | //! You can activate support for `#![no_std]` by adding `#[builder(no_std)]` to your struct |
661 | //! and `#![feature(alloc)] extern crate alloc` to your crate. |
662 | //! |
663 | //! The latter requires the _nightly_ toolchain. |
664 | //! |
665 | //! # Troubleshooting |
666 | //! |
667 | //! ## Gotchas |
668 | //! |
669 | //! - Tuple structs and unit structs are not supported as they have no field |
670 | //! names. |
671 | //! - Generic setters introduce a type parameter `VALUE: Into<_>`. Therefore you can't use |
672 | //! `VALUE` as a type parameter on a generic struct in combination with generic setters. |
673 | //! - The `try_setter` attribute and `owned` builder pattern are not compatible in practice; |
674 | //! an error during building will consume the builder, making it impossible to continue |
675 | //! construction. |
676 | //! - When re-exporting the underlying struct under a different name, the |
677 | //! auto-generated documentation will not match. |
678 | //! - If derive_builder depends on your crate, and vice versa, then a cyclic |
679 | //! dependency would occur. To break it you could try to depend on the |
680 | //! [`derive_builder_core`] crate instead. |
681 | //! |
682 | //! ## Report Issues and Ideas |
683 | //! |
684 | //! [Open an issue on GitHub](https://github.com/colin-kiegel/rust-derive-builder/issues) |
685 | //! |
686 | //! If possible please try to provide the debugging info if you experience unexpected |
687 | //! compilation errors (see above). |
688 | //! |
689 | //! [builder pattern]: https://web.archive.org/web/20170701044756/https://aturon.github.io/ownership/builders.html |
690 | //! [`derive_builder_core`]: https://crates.io/crates/derive_builder_core |
691 | |
692 | #![deny (warnings)] |
693 | #![cfg_attr (not(feature = "std" ), no_std)] |
694 | |
695 | #[cfg (feature = "alloc" )] |
696 | extern crate alloc; |
697 | |
698 | extern crate derive_builder_macro; |
699 | |
700 | mod error; |
701 | |
702 | pub use derive_builder_macro::Builder; |
703 | |
704 | #[doc (inline)] |
705 | pub use error::UninitializedFieldError; |
706 | |
707 | #[doc (hidden)] |
708 | pub mod export { |
709 | pub mod core { |
710 | #[cfg (feature = "alloc" )] |
711 | pub use ::alloc::string; |
712 | #[cfg (not(feature = "std" ))] |
713 | pub use core::*; |
714 | #[cfg (feature = "std" )] |
715 | pub use std::*; |
716 | } |
717 | } |
718 | |