Skip to content

Redundant methods in core::str::StrSlice #15379

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

Closed
apoelstra opened this issue Jul 3, 2014 · 4 comments
Closed

Redundant methods in core::str::StrSlice #15379

apoelstra opened this issue Jul 3, 2014 · 4 comments

Comments

@apoelstra
Copy link
Contributor

In rust-lang/rfcs#153 in was noticed that core::str::StrSlice has some redundant methods:

  • mystr.splitn(n) acts as mystr.split().take(n)
  • mystr.rsplitn(n) acts as mystr.split().rev().take(n)

There isn't any efficiency gain here --- the code in the iterator CharSplitsN just replicates that of iter::Take and iter::Rev. So this is pure redundancy and ought to be removed.

@alexcrichton
Copy link
Member

While similarly named, they do have different semantics. The splitn variants will return the entire string once the iterator has been exhausted. For example, this prints two different things:

fn main() {
    let a = "foo bar baz";

    println!("{}", a.split(' ').take(2).collect::<Vec<&str>>());
    println!("{}", a.splitn(' ', 2).collect::<Vec<&str>>());
}

As in, these are not entirely redundant, but they are indeed unfortunately named.

@bstrie
Copy link
Contributor

bstrie commented Jul 3, 2014

I as well was oblivious to the differing behavior of splitn. An example of another difference:

fn main() {
    let a = "foo bar baz";

    for i in a.split(' ').take(1) { println!("{}", i); }
    for i in a.splitn(' ', 1) {:println!("{}", i); }
}

At the very least, removing rsplitn in favor of .rev().splitn should be acceptable, yeah?

@apoelstra
Copy link
Contributor Author

I don't think so, because rsplitn will have the effect of bundling up all the remaining elements near the start of the string, and there is no way to get this behaviour from splitn.

I'll close this bug since it was a misunderstanding on my part.

@alexcrichton
Copy link
Member

Did you mean .splitn().rev() instead? If so, the semantics are sadly a little different:

For the string foo bar baz, spitn(' ', 1) yields foo then bar baz. If you called splitn().rev() it would yield bar baz then foo. If you call rsplitn(' ', 1) it would yield baz then foo bar, a different result of splitn().rev().

As with split.take/splitn, it's unfortunate to have to have similar names but the semantics do differ slightly :(

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants