Getting Started with Rust: Memory Safety Meets Performance

Rust is a systems programming language focused on safety, speed, and concurrency. Its ownership system eliminates entire classes of bugs at compile time.

## Why Rust?

- Memory safety without garbage collection
- Zero-cost abstractions
- Fearless concurrency
- Excellent error handling with Result/Option
- Growing ecosystem (cargo, crates.io)

## Ownership

```rust
fn main() {
   let s1 = String::from("hello");
   let s2 = s1; // s1 is moved, no longer valid
   // println!("{}", s1); // Error!
   println!("{}", s2); // OK
}
```

## Borrowing

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

fn main() {
   let s = String::from("hello");
   let len = calculate_length(&s);
   println!("{}: {}", s, len);
}
```

## Enums and Pattern Matching

```rust
enum Result<T, E> {
   Ok(T),
   Err(E),
}

fn divide(a: f64, b: f64) -> Result<f64, String> {
   if b == 0.0 {
       Err("Division by zero".to_string())
   } else {
       Ok(a / b)
   }
}

match divide(10.0, 2.0) {
   Ok(val) => println!("Result: {}", val),
   Err(e) => println!("Error: {}", e),
}
```

## Structs

```rust
struct User {
   name: String,
   age: u32,
}

impl User {
   fn greet(&self) -> String {
       format!("Hi, I'm {}", self.name)
   }
}
```

## Error Handling

```rust
use std::fs;

fn read_file(path: &str) -> Result<String, std::io::Error> {
   fs::read_to_string(path)
}

fn main() {
   match read_file("config.txt") {
       Ok(content) => println!("{}", content),
       Err(e) => eprintln!("Error: {}", e),
   }
}
```

## Conclusion

Rust's learning curve is steep but worth it. Start with small CLI tools and gradually build to systems-level projects.

评论
暂无评论