diff options
| author | Steve Klabnik <steve@steveklabnik.com> | 2014-08-28 15:12:18 -0400 |
|---|---|---|
| committer | Steve Klabnik <steve@steveklabnik.com> | 2014-08-30 16:15:46 -0400 |
| commit | 7e4a1459e928791c3905ee4cb30813f222e4c8ca (patch) | |
| tree | 4c1b70d510d14554a33ebb03ad39e9e1e4018734 /src | |
| parent | b5165321e48c1fd8422803fb40693afab7939c8c (diff) | |
| download | rust-7e4a1459e928791c3905ee4cb30813f222e4c8ca.tar.gz rust-7e4a1459e928791c3905ee4cb30813f222e4c8ca.zip | |
note about ref patterns in pointer guide
Fixes #13602
Diffstat (limited to 'src')
| -rw-r--r-- | src/doc/guide-pointers.md | 25 |
1 files changed, 25 insertions, 0 deletions
diff --git a/src/doc/guide-pointers.md b/src/doc/guide-pointers.md index b196997b399..6492400a2cf 100644 --- a/src/doc/guide-pointers.md +++ b/src/doc/guide-pointers.md @@ -729,6 +729,31 @@ This part is coming soon. This part is coming soon. +# Patterns and `ref` + +When you're trying to match something that's stored in a pointer, there may be +a situation where matching directly isn't the best option available. Let's see +how to properly handle this: + +```{rust,ignore} +fn possibly_print(x: &Option<String>) { + match *x { + // BAD: cannot move out of a `&` + Some(s) => println!("{}", s) + + // GOOD: instead take a reference into the memory of the `Option` + Some(ref s) => println!("{}", *s), + None => {} + } +} +``` + +The `ref s` here means that `s` will be of type `&String`, rather than type +`String`. + +This is important when the type you're trying to get access to has a destructor +and you don't want to move it, you just want a reference to it. + # Cheat Sheet Here's a quick rundown of Rust's pointer types: |
