Skip to content

Instantly share code, notes, and snippets.

@erpe
Last active August 29, 2015 14:12
Show Gist options
  • Save erpe/18920d7ff0e3be19e05d to your computer and use it in GitHub Desktop.
Save erpe/18920d7ff0e3be19e05d to your computer and use it in GitHub Desktop.
rust - String and str
fn main() {
let mut txt = "Hello, World!".to_string(); // txt: String
println!("first its: {}", txt);
txt = get_pling(txt);
println!("then its: {}",txt);
add_in_place_plong(&mut txt); // passes a mutable reference
println!("finally its: {}", txt);
let y = txt.as_slice(); // y: &str
print_foo(y); // borrow y to print_foo
println!("still here: {}", y);
let z = box y; // copy
say_foobar(z); // passed ownership forward
// would error cause ownership moved
//println!("errors: {}", z);
println!("works: {}", y);
}
// copies given string modfies and returns
fn get_pling(arg: String) -> String {
let mut ret = arg;
ret.push_str("\n about 42");
ret.to_string()
}
// modifies given reference
fn add_in_place_plong(arg: &mut String) {
arg.push_str("\n working...");
}
// borrow arg
fn print_foo(arg: &str) {
println!("summed up: {}", arg);
}
// becomes owner
fn say_foobar(arg: Box<&str>) {
println!("saying: {}", *arg);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment