Skip to content

Slight modification to the as_ref example of std::option::Option #48509

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Mar 6, 2018
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/libcore/option.rs
Original file line number Diff line number Diff line change
Expand Up @@ -233,10 +233,10 @@ impl<T> Option<T> {
/// [`usize`]: ../../std/primitive.usize.html
///
/// ```
/// let num_as_str: Option<String> = Some("10".to_string());
/// let num_as_str: Option<String> = Some("12".to_string());
Copy link

@neandrake neandrake Feb 25, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To address the problem more directly it might make sense to change this completely -- the fact that the string contents are numbers is irrelevant. Maybe instead

let text: Option<String> = Some("Hello, World!".to_string());
let text_length: Option<usize> = text.as_ref().map(|t| t.len());

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's a good idea. I'll change that.

/// // First, cast `Option<String>` to `Option<&String>` with `as_ref`,
/// // then consume *that* with `map`, leaving `num_as_str` on the stack.
/// let num_as_int: Option<usize> = num_as_str.as_ref().map(|n| n.len());
/// let num_length: Option<usize> = num_as_str.as_ref().map(|n| n.len());
/// println!("still can print num_as_str: {:?}", num_as_str);
/// ```
#[inline]
Expand Down