Skip to content

Commit 2f09b47

Browse files
authored
Merge pull request #200 from greyblake/add-more-doc-on-as-ref
Add more docs on AsRef
2 parents 7432aa2 + eabab89 commit 2f09b47

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

README.md

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -388,6 +388,18 @@ If you are dealing with a heap allocated type (e.g. `String`) you should conside
388388

389389
## Recipes
390390

391+
### Obtaining a reference to the inner value
392+
393+
The function `.into_inner()` takes ownership of the newtype and returns its inner type. However, if you only need to borrow the inner value (rather than consume it), you can derive `AsRef`. This allows you to call `as_ref()` to obtain a reference to the underlying data:
394+
395+
```rs
396+
#[nutype(derive(AsRef))]
397+
struct Username(String);
398+
399+
let username = Username::new("Jack");
400+
assert_eq!(username.as_ref(), "Jack");
401+
```
402+
391403
### Derive `Default`
392404

393405
```rs

nutype/src/lib.rs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -441,6 +441,20 @@
441441
//!
442442
//! ## Recipes
443443
//!
444+
//! ### Obtaining a reference to the inner value
445+
//!
446+
//! The function `.into_inner()` takes ownership of the newtype and returns its inner type. However, if you only need to borrow the inner value (rather than consume it), you can derive `AsRef`. This allows you to call `as_ref()` to obtain a reference to the underlying data:
447+
//!
448+
//! ```rs
449+
//! use nutype::nutype;
450+
//!
451+
//! #[nutype(derive(AsRef))]
452+
//! struct Username(String);
453+
//!
454+
//! let username = Username::new("Jack");
455+
//! assert_eq!(username.as_ref(), "Jack");
456+
//! ```
457+
//!
444458
//! ### Derive `Default`
445459
//!
446460
//! ```

0 commit comments

Comments
 (0)