Return a string literal from a function

Have you ever seen the MST3K episode "Space Mutiny?" There's a running gag in that episode where they call the main character funny names like "Biff VanderBeef" or "Dirk FirstPound." You see the pattern. "First PrefixSuffix."

I've written a Space Mutiny name generator years ago in Python when learning that language, so I'm trying it out in Rust.

So, I've got three arrays full of string literals, one each for first, prefix and suffix. I need to generate a random number between 0 and the length of the array, get the corresponding array element, and pump it into println!. In fact, this works:

use rand::Rng;

fn main() {
let first = ["John", "Biff", "Doug", "Dirk", "Thick", "Spunk"];
let prefix = ["Vander", "McLarge", "Beef", "Head", "Lift", "Dunder", "Squat"];
let suffix = ["Pound", "Slam", "Thrust", "Crunch", "Huge", "Chunk", "Cheese"];

let first_index = rand::thread_rng().gen_range(0, first.len());
let prefix_index = rand::thread_rng().gen_range(0, prefix.len());
let suffix_index = rand::thread_rng().gen_range(0, suffix.len());

println!("{} {}{}", first[first_index], prefix[prefix_index], suffix[suffix_index]);

}

now, I do the same thing three times there, so let's refactor that as a function. Basically, pass it an array arr, generate a random number between 0 and arr.len(), and return the element of that array. This should be trivial, but we have to keep track of type, scope, ownership, lifetime, birthday, astrological sign, favorite soup and preferred brand of toilet paper, and it's just beyond me. I think it should look something like:

fn rand_name(arr: &str) -> &str {
let index = rand::thread_rng().gen_range(0, arr.len());
arr[index]
}

I can't satisfy the compiler on this one, and I've run out of google.

You've declared rand_name as a function that takes an immutable reference to a single string, rather than an immutable reference to an array of strings. Consequently your arr.len() is the length of a single UTF-8 string, not of an array. Indexing is not defined on UTF-8 strings because characters are potentially multi-byte.

2 Likes

In order to take an array of strings, use a slice type: &[&str].

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.