1

Given the array:

static STRS_UPPER: [&'static str; 3] = ["FOO", "BAR", "BAZ"];

What is a succinct way of passing a mapped representation (for example, making all strings lowercase) of the above array to a function with the signature:

fn print_str_slice(slice: &[&str]);

The above type parameters are fixed. I cannot change the signature of print_str_slice or the type of STRS_UPPER.

What I am doing currently:

let strings_lower = STRS_UPPER.iter()
    .map(|s| s.to_string().to_ascii_lowercase())
    .collect::<Vec<_>>();

print_str_slice(strings_lower.iter()
    .map(AsRef::as_ref)
    .collect::<Vec<_>>()
    .as_slice()
);

Can this be done in a cleaner way, perhaps without the intermediary vector strings_lower?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
rjsberry
  • 336
  • 1
  • 7
  • I believe your question is answered by the answers of [Convert Vec into a slice of &str in Rust?](https://stackoverflow.com/q/41179659/155423). If you disagree, please [edit] your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster Oct 30 '18 at 19:48
  • TL;DR: no, that's the best you can do with the constraints you are given. – Shepmaster Oct 30 '18 at 19:49
  • I thought as much. I understand the requirement of the temporary `String` vector, but I am doing a lot of the conversions as in my question. Thanks for your reply, I'm happy to have the question marked as already answered. – rjsberry Oct 30 '18 at 19:53
  • Can you say *why* you cannot change the signature of `print_str_slice`? Is it in a different crate? My normal solution would be to change it to `fn foo(words: I) where I: IntoIterator, I::Item: AsRef` to handle *many* types of input. – Shepmaster Oct 30 '18 at 20:01
  • Yes, the function exists in another crate. The signature is actually `(mut self, names: &[&'b str])`, and the lifetime `b` is quite tightly wound into the implementation. – rjsberry Oct 30 '18 at 20:48

0 Answers0