I want to do the following in Rust:
let (command, options) = message.splitn(2, ' ');
This can't be done because of:
expected struct `std::str::SplitN`, found tuple
The split will always be two and I like having named variables. The message may not contain a space character.
The splitn()
method returns an iterator over the parts, so the only way to access them is to actually iterate over them. If you know that there always will be two parts, you can do this:
let mut iter = message.splitn(2, ' ');
let command = iter.next().unwrap();
let options = iter.next().unwrap();
This will work fine as long as message
contains at least one space character. For a message without a space, this will panic on the last line, since the iterator is already terminated, so you would call unwrap()
on None
. (Note that you need 2 as the first argument to splitn()
if you want to get two items.)
Using the itertools
crate, you could use the collect_tuple()
method:
use itertools::Itertools;
let (command, options) = message.splitn(2, ' ').collect_tuple().unwrap();
This will also panic if the iterator returns only a single item.
As pointed out in the comments, another option is to use str::split_at()
together with str::find()
:
let (command, options) = message.split_at(message.find(' ').unwrap());
Note that the space character will be included in options
with this solution, whereas the other approaches don't include it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With