Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unpack a splitn into a tuple in Rust? [duplicate]

Tags:

split

tuples

rust

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.

like image 721
Folaht Avatar asked Jun 08 '20 07:06

Folaht


Video Answer


1 Answers

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.

like image 64
Sven Marnach Avatar answered Oct 17 '22 03:10

Sven Marnach