Pybites Logo Rust Platform

Basic Structs

Easy +2 pts

🎯 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 struct defines fields. The impl block defines methods. In Python, both live inside the class.
  • &self is explicit. Python's self is always a reference. Rust makes you write &self (borrow) vs self (consume) — you choose whether the method keeps the struct alive.
  • Fields are private by default. Rust uses pub to opt-in to visibility (covered in a later exercise). Python uses _underscore conventions.

Creating struct instances

Rust doesn't have constructors like Python's __init__. You create instances directly:

let city = City {
    name: String::from("Tokyo"),
    country: String::from("Japan"),
    population: 14_000_000,
};

Or you can define a new function by convention (not a language feature):

impl City {
    fn new(name: &str, country: &str, population: u64) -> Self {
        City {
            name: name.to_string(),
            country: country.to_string(),
            population,  // shorthand when field name matches variable name
        }
    }
}

Login to see the full task and start coding.

This is a premium exercise

Log in to unlock the full exercise and start coding.

Login to access this exercise