Skip to content

structs3 doesn't actually practice method syntax #2286

@senekor

Description

@senekor

The exercise structs3 is supposed to practice methods, but it just asks the user to add return types (same syntax as normal functions) and implementing the function bodies.

I made a different exercise that asks users to refactor a bunch of free-standing functions into methods / associated functions. Users have to type all the new syntax related to methods themselves:

  • create an impl block
  • use a Self type (checked by clippy with use_self = "warn")
  • write a self parameter that takes ownership and one that takes a mutable reference

I think this would be much better for practicing method syntax. Open question: Should something like this replace structs3 or be added as structs4? I'll be happy to open a PR if that's settled. Here's my exercise:

// Structs contain data, but can also have logic. In this exercise, we have
// defined the `Fireworks` struct and a couple of functions that work with it.
// Turn these free-standing functions into methods and associated functions
// to express that relationship more clearly in the code.

struct Fireworks {
    rockets: usize,
}

// TODO: Turn this function into an associated function on `Fireworks`.
fn new_fireworks() -> Fireworks {
    Fireworks { rockets: 0 }
}

// TODO: Turn this function into a method on `Fireworks`.
fn add_rockets(fireworks: &mut Fireworks, rockets: usize) {
    fireworks.rockets += rockets
}

// TODO: Turn this function into a method on `Fireworks`.
fn start(fireworks: Fireworks) -> String {
    if fireworks.rockets < 5 {
        String::from("small")
    } else if fireworks.rockets < 20 {
        String::from("medium")
    } else {
        String::from("big")
    }
}

fn main() {
    // You can optionally experiment here.
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn start_some_fireworks() {
        let mut f = Fireworks::new();
        f.add_rockets(3);
        assert_eq!(f.start(), "small");

        let mut f = Fireworks::new();
        f.add_rockets(15);
        assert_eq!(f.start(), "medium");

        let mut f = Fireworks::new();
        f.add_rockets(100);
        assert_eq!(Fireworks::start(f), "big");
        // We don't use method syntax in the last test to ensure the `start`
        // function takes ownership of the fireworks.
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions