Rust Programming: What is Method Syntax?

0

Method syntax in Rust is the way that we call methods on structs. Methods are similar to functions, but they are defined within the context of a struct. This means that the first parameter of a method is always the struct instance that the method is being called on. For example, let's say we have a struct called `Rectangle` with two fields, `width` and `height`. We can define a method called `area` that calculates the area of the rectangle:

struct Rectangle {

    width: u32,

    height: u32,

}


impl Rectangle {

    fn area(&self) -> u32 {

        self.width * self.height

    }

}

To call the `area` method on a `Rectangle` instance, we would use the following syntax:

let rect = Rectangle { width: 10, height: 20 };

let area = rect.area();

The `area` variable will now contain the area of the rectangle, which is 200.

Here is another example of method syntax in Rust:

struct Person {

    name: String,

    age: u32,

}


impl Person {

    fn say_hello(&self) {

        println!("Hello, my name is {}!", self.name);

    }

}


fn main() {

    let person = Person { name: "John Doe".to_string(), age: 30 };

    person.say_hello();

}

In this example, the `say_hello` method is called on the `person` struct instance. The `say_hello` method simply prints a greeting to the console, using the `person` struct instance's `name` field.

Post a Comment

0Comments
Post a Comment (0)