mirror of https://github.com/rust-lang/rustlings
Add some exercises about Strings and &strs!
parent
ce3b710b13
commit
93869014f4
@ -0,0 +1,45 @@
|
||||
// Make me compile without changing the function signature! Scroll down for hints :)
|
||||
|
||||
fn main() {
|
||||
let answer = current_favorite_color();
|
||||
println!("My current favorite color is {}", answer);
|
||||
}
|
||||
|
||||
fn current_favorite_color() -> String {
|
||||
"blue"
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
// The `current_favorite_color` function is currently returning a string slice with the `'static`
|
||||
// lifetime. We know this because the data of the string lives in our code itself -- it doesn't
|
||||
// come from a file or user input or another program -- so it will live as long as our program
|
||||
// lives. But it is still a string slice. There's one way to create a `String` by converting a
|
||||
// string slice covered in the Strings chapter of the book, and another way that uses the `From`
|
||||
// trait.
|
@ -0,0 +1,42 @@
|
||||
// Make me compile without changing the function signature! Scroll down for hints :)
|
||||
|
||||
fn main() {
|
||||
let guess1 = "blue".to_string(); // Try not changing this line :)
|
||||
let correct = guess_favorite_color(guess1);
|
||||
if correct {
|
||||
println!("You guessed correctly!");
|
||||
} else {
|
||||
println!("Nope, that's not it.");
|
||||
}
|
||||
}
|
||||
|
||||
fn guess_favorite_color(attempt: &str) -> bool {
|
||||
attempt == "green"
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
// Yes, it would be really easy to fix this by just changing the value bound to `guess1` to be a
|
||||
// string slice instead of a `String`, wouldn't it?? There is a way to add one character to line
|
||||
// 5, though, that will coerce the `String` into a string slice.
|
@ -0,0 +1,18 @@
|
||||
// Ok, here are a bunch of values-- some are `Strings`, some are `&strs`. Your
|
||||
// task is to call one of these two functions on each value depending on what
|
||||
// you think each value is. That is, add either `string_slice` or `string`
|
||||
// before the parentheses on each line. If you're right, it will compile!
|
||||
|
||||
fn string_slice(arg: &str) { println!("{}", arg); }
|
||||
fn string(arg: String) { println!("{}", arg); }
|
||||
|
||||
fn main() {
|
||||
("blue");
|
||||
("red".to_string());
|
||||
(String::from("hi"));
|
||||
(format!("Interpolation {}", "Station"));
|
||||
(&String::from("abc")[0..1]);
|
||||
(" hello there ".trim());
|
||||
("Happy Monday!".to_string().replace("Mon", "Tues"));
|
||||
("mY sHiFt KeY iS sTiCkY".to_lowercase());
|
||||
}
|
Loading…
Reference in New Issue