rust

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Rust

Rust

A language empowering everyone to build reliable and efficient software.
一门赋能所有人构建可靠且高效软件的编程语言。

When to Use

适用场景

  • Systems programming (drivers, OS)
  • WebAssembly
  • Performance-critical applications
  • Command-line tools (great developer experience)
  • 系统编程(驱动程序、操作系统)
  • WebAssembly
  • 性能关键型应用
  • 命令行工具(极佳的开发者体验)

Quick Start

快速入门

rust
fn main() {
    println!("Hello, World!");

    let mut x = 5; // mutable
    x = 6;

    let y = 10; // immutable by default
}
rust
fn main() {
    println!("Hello, World!");

    let mut x = 5; // 可变的
    x = 6;

    let y = 10; // 默认不可变
}

Core Concepts

核心概念

Ownership & Borrowing

所有权与借用

The borrow checker ensures rules are followed at compile time.
  • Each value has a single owner.
  • You can have multiple immutable borrows OR one mutable borrow, but not both simultaneously.
借用检查器确保在编译时遵循规则。
  • 每个值有且仅有一个所有者
  • 你可以拥有多个不可变借用 或者一个可变借用,但不能同时拥有两者。

Lifetimes

生命周期

Ensuring references remain valid for as long as they are used.
确保引用在其使用期间始终有效。

Traits

Trait

Similar to interfaces, defining shared behavior.
类似于接口,用于定义共享行为。

Best Practices

最佳实践

Do:
  • Embrace the borrow checker (it's your friend)
  • Use
    Result<T, E>
    and
    Option<T>
    for error handling
  • Use
    cargo clippy
    for linting
  • Use
    match
    for exhaustive pattern matching
Don't:
  • Use
    unsafe
    unless absolutely necessary
  • unwrap()
    in production code (use proper error handling)
建议:
  • 接纳借用检查器(它是你的好帮手)
  • 使用
    Result<T, E>
    Option<T>
    进行错误处理
  • 使用
    cargo clippy
    进行代码检查
  • 使用
    match
    进行穷尽式模式匹配
不建议:
  • 除非绝对必要,否则不要使用
    unsafe
  • 不要在生产代码中使用
    unwrap()
    (请使用适当的错误处理方式)

References

参考资料