Please update your browser to view this website! Use the latest version of Chrome, Firefox or Safari for the best experience.

Example: Polygons

Warning: This documentation is still being written. Some pages may be out-of-date or incomplete. Some links may not work and the URLs may change in the future. More will be completed soon. :)

The goal of this lesson is to create a function that can draw any n-sided polygon where n ≥ 3. We’ll start with this program as the template for our solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
use turtle::Turtle;

fn main() {
    let mut turtle = Turtle::new();

    // The number of sides of the polygon to draw (>= 3)
    let sides = 3;
    polygon(&mut turtle, sides)
}

fn polygon(turtle: &mut Turtle, sides: usize) {
    assert!(sides >= 3, "The number of sides must be >= 3");

    //TODO
}

  • Use this function to make other functions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
fn triangle(turtle: &mut Turtle) {
    polygon(turtle, 3)
}

fn square(turtle: &mut Turtle) {
    polygon(turtle, 4)
}

fn pentagon(turtle: &mut Turtle) {
    polygon(turtle, 5)
}

fn hexagon(turtle: &mut Turtle) {
    polygon(turtle, 6)
}