Rust for JavaScript Developers
Rust offers memory safety and performance. Here's how to get started coming from JavaScript.
Setting Up Rust
# Install Rust
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
# Create a new project
cargo new my_project
cd my_project
Variables and Types
// JavaScript
let name = "Alice";
let age = 30;
// Rust - immutable by default
let name = "Alice"; // &str
let age: i32 = 30; // explicit type
let mut count = 0; // mutable
Ownership - The Key Concept
fn main() {
let s1 = String::from("hello");
let s2 = s1; // s1 is moved, no longer valid
// This would error:
// println!("{}", s1);
// Use clone for copies
let s3 = s2.clone();
}
Error Handling
use std::fs;
fn read_file(path: &str) -> Result {
fs::read_to_string(path)
}
fn main() {
match read_file("config.txt") {
Ok(content) => println!("{}", content),
Err(e) => eprintln!("Error: {}", e),
}
// Or use ? operator
let content = read_file("config.txt")?;
}
Structs and Implementations
struct User {
name: String,
age: u32,
}
impl User {
fn new(name: &str, age: u32) -> Self {
User {
name: name.to_string(),
age,
}
}
fn greet(&self) {
println!("Hello, {}!", self.name);
}
}
Rust's learning curve is steep but rewards you with fast, safe code.
Comments (0)
Leave a Comment
No comments yet. Be the first to share your thoughts!