Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

\u6240\u6709\u6743\u7cfb\u7edf

Rust \u7684\u6838\u5fc3\u7279\u6027\u4e4b\u4e00\u5c31\u662f\u6240\u6709\u6743\u7cfb\u7edf\u3002

\u89c4\u5219

  1. Rust \u4e2d\u6bcf\u4e2a\u503c\u90fd\u6709\u4e00\u4e2a\u6240\u6709\u8005 (owner)
  2. \u540c\u4e00\u65f6\u95f4\u53ea\u80fd\u6709\u4e00\u4e2a\u6240\u6709\u8005
  3. \u5f53\u6240\u6709\u8005\u79bb\u5f00\u4f5c\u7528\u57df\u65f6\uff0c\u503c\u88ab\u4e22\u5f03
fn main() {
    let s1 = String::from("hello");
    let s2 = s1; // s1 \u7684\u6240\u6709\u6743\u8f6c\u79fb\u7ed9 s2

    // println!("{}", s1); // \u7f16\u8bd1\u9519\u8bef\uff01s1 \u5df2\u4e0d\u53ef\u7528
    println!("{}", s2); // OK
}

Warning

\u6ce8\u610f\u533a\u5206\u79fb\u52a8\u8bed\u4e49\u548c\u590d\u5236\u8bed\u4e49\u3002\u5bf9\u4e8e\u5806\u4e0a\u6570\u636e\uff08\u5982 String\uff09\uff0c\u8d4b\u503c\u4f1a\u8f6c\u79fb\u6240\u6709\u6743\uff1b\u5bf9\u4e8e\u6808\u4e0a\u6570\u636e\uff08\u5982 i32\uff09\uff0c\u8d4b\u503c\u4f1a\u590d\u5236\u503c\u3002

\u501f\u7528\u4e0e\u5f15\u7528

fn calculate_length(s: &String) -> usize {
    s.len()
}

fn main() {
    let s1 = String::from("hello");
    let len = calculate_length(&s1);
    println!("'{}' \u7684\u957f\u5ea6\u662f {}", s1, len);
}