Basic Structs
Easy
+2 pts
Intro to Rust
12/15
🎯 In Python, you'd use a class or dataclass to group related data:
from dataclasses import dataclass
@dataclass
class City:
name: str
country: str
population: int
def summary(self) -> str:
return f"{self.name} ({self.country}) — population: {self.population}"
Rust's equivalent is a struct with an impl block for methods:
struct City {
name: String,
country: String,
population: u64,
}
impl City {
fn summary(&self) -> String {
format!(
"{} ({}) — population: {}",
self.name, self.country, self.population
)
}
}
Key differences from Python:
- Data and methods are separate. The
structdefines fields. Theimplblock defines methods. In Python, both live inside theclass. &selfis explicit. Python'sselfis always a reference. Rust makes you write&self(borrow) vsself(consume) — you choose whether the method keeps …
Login to see the full exercise.