Learn methods in rust using simple step by step examples.

Example 1: Simple methods example.

This example will introduce you to method creation and invocation.

Step 1: Create Project

The first step is to create a Rust project .

Creating a Project Directory

Open a terminal and enter the following commands to make a projects directory and an inner directory for this example within that projects directory.

For Linux, macOS, and PowerShell on Windows, enter this:

$ mkdir ~/projects
$ cd ~/projects
$ mkdir your_example_name
$ cd your_example_name

For Windows CMD, enter this:

> mkdir "%USERPROFILE%\projects"
> cd /d "%USERPROFILE%\projects"
> mkdir your_example_name
> cd your_example_name

Step 2: Dependencies

No dependencies are needed for this project.

Step 3: Write Code

Create a file named main.rs and add the following code:

main.rs

#![allow(dead_code)]

use std::f64::consts::PI;

#[derive(Debug)]
struct Point {
    x: f64,
    y: f64
}
#[derive(Debug)]
enum Shape {
    Circle { center: Point, radius: f64 },
    Rectangle { top_left: Point, bottom_right: Point }
}
impl Shape {
    fn draw(&self) {
        match *self {
            Shape::Circle{center: ref p, radius: ref f} => draw_circle(p, f),
            Shape::Rectangle{top_left: ref p1, bottom_right: ref p2} => draw_rectangle(p1, p2)
        }
    }
    pub fn new_circle(area: f64) -> Shape {
        let center = Point{x: 0.0, y: 0.0};
        let radius = (area / PI).sqrt();
        Shape::Circle{center: center, radius: radius}
    }
}
fn draw_circle(p: &Point, f: &f64) {
    println!("draw_circle({:?}, {:?})", p, f);
}
fn draw_rectangle(p1: &Point, p2: &Point) {
    println!("draw_rectangle({:?}, {:?})", p1, p2);
}
fn main() {
    let c = Shape::Circle{center: Point { x: 1.0, y: 2.0 }, radius: 3.0};
    c.draw();

    let r = Shape::Rectangle{top_left: Point{x: 1.0, y: 2.0}, bottom_right: Point{x: 2.0, y: 3.0}};
    r.draw();

    let c2 = Shape::new_circle(42.5);
    println!("c2={:?}", c2);
    c2.draw();
}

Result

If you run the above code you will get the following:

draw_circle(Point { x: 1.0, y: 2.0 }, 3.0)
draw_rectangle(Point { x: 1.0, y: 2.0 }, Point { x: 2.0, y: 3.0 })
c2=Circle { center: Point { x: 0.0, y: 0.0 }, radius: 3.6780660900548137 }
draw_circle(Point { x: 0.0, y: 0.0 }, 3.6780660900548137)

Run

Save the code and run your code as follows:

Assuming our file name is main.rs, first compile it

$ rustc main.rs

then run it:

$ ./main

On Windows, enter the command .\main.exe instead of ./main:

compile:

> rustc main.rs

then run it:

> .\main.exe

Categorized in: