Skip to content

Latest commit

 

History

History
108 lines (79 loc) · 2.4 KB

File metadata and controls

108 lines (79 loc) · 2.4 KB
title Smart Compiler
slug smart-compiler

Compile-time Errors

Rust focuses on strict code hygiene, and the compiler generates a highly specific set of warnings and errors to make it easier to identify and solve them.

Typos

struct Person {
    name: String,
    company_name: String,
}

fn main() {
    let steve = Person {
        name: "Steve Jobs".to_string(),
        company_name: "Apple".to_string(),
    };

    // Destructuring fields' values to a and b
    let Person {fname: a, company_name: b} = steve;

    println!("{a} {b}");
}

[!caution] Compile-time Error Compile-time Error: Typos

Ownership

#![allow(unused)] //💡 A lint attribute used to suppress the warning; unused variable: `b`
fn main() {
    let a = vec![1, 2, 3];
    let b = a;

    println!("{:?}", a);
}

[!caution] Compile-time Error Compile-time Error: Ownership

Lifetimes

fn main() {
    let steve = Person{fname: "Steve", lname: "Jobs"};
    steve.intro();
}

struct Person {
    fname: &str,
    lname: &str,
}

impl Person {
    fn intro(&self) {
        println!("Hello! I am {} {}.", self.fname, self.lname)
    }
}

[!caution] Compile-time Error Compile-time Error: Lifetimes

Concurrency

use std::{rc::Rc, thread};

fn main() {
    let data = Rc::new(vec![1, 2, 3]);

    let value1 = Rc::clone(&data);
    let handle1 = thread::spawn(move || {
        println!("{:?}", &value1);
    });

    let value2 = Rc::clone(&data);
    let handle2 = thread::spawn(move || {
        println!("{:?}", &value2);
    });

    handle1.join().unwrap();
    handle2.join().unwrap();
}

[!caution] Compile-time Error Compile-time Error: Concurrency

Error Codes

  • Rust's error codes consist of the letter E followed by four digits.
  • Each code corresponds to a specific kind of error, and rustc --explain <CODE> provides more details to help to identify the error.
  • The same explanations are also available in the Rust Error Codes Index.

For example, rustc --explain E0571 shows the following output in the console, and the same content is also available at https://doc.rust-lang.org/error_codes/E0571.html.

[!search] Explain Error Codes