Skip to content

Instantly share code, notes, and snippets.

@robert-saramet
Created April 10, 2023 10:48
Show Gist options
  • Select an option

  • Save robert-saramet/c9b776e472f4971f04d1bbf5015e9813 to your computer and use it in GitHub Desktop.

Select an option

Save robert-saramet/c9b776e472f4971f04d1bbf5015e9813 to your computer and use it in GitHub Desktop.
Comparison between the String and str types in Rust, including example functions and the effects of how the parameters are passed. This is only my understanding as a beginner and I'm not sure everything is correct.
// Idiomatic
// Modifies string_var in place; doesn't return anything
// The original string_var remains valid
fn takes_string_ref_no_return(string_var: &mut String) {
string_var.push_str("world");
}
// Idiomatic
// Returns a new owned String
// The original str_var also remains valid
fn takes_str_ref_returns_string(str_var: &str) -> String {
// Clones str_var to make it owned
let mut string_var = str_var.to_owned();
string_var.push_str("world");
string_var
}
// Idiomatic but not ideak
// Returns a new owned String
// The original string_var passed into the fn is moved and becomes invalid to the caller
fn takes_string_with_ownership(mut string_var: String) -> String {
string_var.push_str("world");
string_var
}
// Bad idea
// Modifies string_var in place and also returns a copy of it
// The original string_var remains valid
fn takes_string_ref_with_return(string_var: &mut String) -> String {
string_var.push_str("world");
string_var.to_string()
}
// INVALID!!!
// No such thing as &mut str
fn takes_str_ref_no_return(str_var: &mut str) {
// string_var below is dropped at end of scope
let string_var = String::from(str_var);
string_var.push_str("world");
// str_var below would be a dangling reference
str_var = &string_var; // can't mutate a str
}
fn main() {
let string_var = String::from("hello "); // owned String, growable, mutable
let str_var = "hello "; // str slice: reference to String, fixed size, immutable
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment