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