A compiler checks code before it runs. Rust’s compiler is strict: code that breaks its rules will not run until you fix it. Its messages often point to the problem and suggest a change, so an error can be a useful next step rather than a dead end. section 1.1 section 1.1.2
Fix a String one message at a time
Suppose you create a String, add an exclamation mark, and print it. The first attempt has three problems: the print call needs a comma, the starting text needs conversion to a String, and `push` needs a character in single quotes. After those fixes, the compiler finds one more problem: the variable must be declared `mut` before it can be changed. section 1.1.2
error: expected `,`, found `my_name` | 4 | println!("{}" my_name); | ^^^^^^^ expected `,` error[E0308]: mismatched types --> src/main.rs:2:27 | 2 | let my_name: String = "Dave"; | ------ ^^^^^^- help: try using a conversion method: `.to_string()` | | | | | expected struct `String`, found `&str` | expected due to this error[E0308]: mismatched types --> src/main.rs:3:18 | 3 | my_name.push("!"); | ---- ^^^ expected `char`, found `&str` | | | arguments to this function are incorrect | help: if you meant to write a `char` literal, use single quotes | 3 | my_name.push('!'); | ~~~
The first compiler messages identify three separate errors and suggest how to fix them. section 1.1.2
The next message asks for a mutable variable: adding to the String changes it. section 1.1.2
fn main() {
let mut my_name: String = "Dave".to_string();
my_name.push('!');
println!("{}", my_name);
}
With `mut` added, the corrected program runs. section 1.1.2
Not every message means the program is broken. An unused-variable warning can appear even when code compiles and runs. The compiler also works out many variable types for you: `let my_number = 8` gets the default integer type `i32`, while `let my_number: u8 = 8` states a different choice. When it cannot determine the type—or you want another one—you can specify it. section 1.1.2 section 1.4








