Teach me Rust.
- User
Teach me Rust.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Teach me Rust.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
I'll help you learn Rust! Here's a structured introduction to get you started:
Rust is a systems programming language focused on:
Install Rust via rustup (recommended):
# For Linux/macOS:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
# For Windows:
# Download and run rustup-init.exe from https://www.rust-lang.org/tools/install
Verify installation:
rustc --version # Should show version >= 1.0
Create hello.rs:
fn main() {
println!("Hello, Rust!");
}
Compile & run:
rustc hello.rs && ./hello # Linux/macOS
.\hello.exe # Windows
let x = 5; // Immutable (default)
let mut y = 10; // Mutable
const MAX_POINTS: u32 = 100_000; // Constant
// Primitive types
let integer: i32 = -42; // Signed integer
let unsigned: u64 = 100; // Unsigned integer
let float: f64 = 3.14; // Double-precision float
let boolean: bool = true; // Boolean
let character: char = '😻'; // Unicode character
fn add(a: i32, b: i32) -> i32 {
a + b // Return value (no semicolon!)
}
if x < 0 {
println!("Negative");
} else if x == 0 {
println!("Zero");
} else {
println!("Positive");
}
// Infinite loop
loop {
println!("Again!");
break; // Exit loop
}
// While loop
while x < 5 {
x += 1;
}
// For loop (iterator-based)
for i in 0..3 { // 0, 1, 2
println!("{}", i);
}
(Rust's most unique feature)
fn main() {
let s1 = String::from("hello");
let s2 = s1; // Ownership moves to s2
// println!("{}", s1); // Error: s1 is no longer valid
}
Pass references instead of transferring ownership:
fn calculate_length(s: &String) -> usize {
s.len() // s is a reference (borrowed)
}
fn main() {
let s = String::from("hello");
let len = calculate_length(&s); // Pass reference
println!("Length: {}", len); // s is still valid
}
Create with Cargo (Rust's package manager):
cargo new guessing_game
cd guessing_game
cargo run
Modify src/main.rs:
use rand::Rng;
use std::cmp::Ordering;
use std::io;
fn main() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1..=100);
loop {
println!("Please input your guess.");
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
break;
}
}
}
}
Add to Cargo.toml:
[dependencies]
rand = "0.8.5"
Run with:
cargo run
Would you like me to explain any specific topic in more depth?