Using strings in functions

It's idiomatic and performant to pass string slices to functions. Here's an example:

// string_slices_func.rs

fn say_hello(to_whom: &str) {
println!("Hey {}!", to_whom)
}

fn main() {
let string_slice: &'static str = "you";
let string: String = string_slice.into();
say_hello(string_slice);
say_hello(&string);
}

To the astute observer, the say_hello method also worked with a &String type. Internally, &String automatically coerces to &str, due to the type coercion trait Deref implemented for &String to &str. This is because String implements Deref for the str type.

Here, you can see why I stressed the point earlier. A string slice is an acceptable input parameter not only for actual string slice references but also for String references! So, once more: if you need to pass a string to your function, use the string slice, &str.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset