Rust FAQs

less than 1 minute read

Q. Whats the difference between,

version 1

fn somefunc(text: &String) {...}

let x = String::from("Pew");
somefunc(&x)

version 2

fn somefunc(text: String) {...}

let x = String::from("Pew");
somefunc(x.clone())

version 1 is more efficient because we are passing reference of the original variable. In other words, somefunc borrows reference to x

version 2 is less efficient as it creates a copy. The function owns the cloned variable and the main owns the original.

Q. When do I use &str vs String type?

First thing to note is that, &str is all encompassing as in, it accepts both String and &str data passed in a fn.

If there isn’t a need to pass the ownership, use &str, else use String.

Categories:

Updated:

Leave a comment