Skip to content
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

Add documentation on str::starts_with #120764

Merged
merged 3 commits into from
Feb 10, 2024
Merged
Changes from 2 commits
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
14 changes: 14 additions & 0 deletions library/core/src/str/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1160,6 +1160,12 @@ impl str {
/// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
/// function or closure that determines if a character matches.
///
/// Note that there is a footgun to this method when using a slice of [`char`]s.
/// Some users may expect that a slice of chars will behave similarly to a `&str` with this method.
/// That is not currently the case. When you pass a slice of [`char`]s to this method, it will return true
/// if any of the [`char`]s in the slice is the first [`char`] of this string slice. It does not work for
/// sequentially comparing a slice of [`char`]s to a string slice. See the second example below.
Copy link
Member

Choose a reason for hiding this comment

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

I don't think this wording (with "footgun", "some users", "currently", etc.) is very useful.

How about instead just adding a bit more detail to the paragraph above? Maybe something in this direction?

-    /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
-    /// function or closure that determines if a character matches.
+    /// The [pattern] can be a `&str` to check for a prefix,
+    /// or a [`char`], slice of [`char`]s, or function or closure 
+    /// to check the first character for a match.

///
/// [`char`]: prim@char
/// [pattern]: self::pattern
///
Expand All @@ -1171,6 +1177,14 @@ impl str {
/// assert!(bananas.starts_with("bana"));
/// assert!(!bananas.starts_with("nana"));
/// ```
///
/// ```
/// let bananas = "bananas";
///
/// // Note that both of these assert successfully.
/// assert!(bananas.starts_with(&['b', 'a', 'n', 'a']));
/// assert!(bananas.starts_with(&['a', 'b', 'c', 'd']));
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
pat.is_prefix_of(self)
Expand Down
Loading