Back to articles
[Rust Guide] 5.3. Methods on Structs

[Rust Guide] 5.3. Methods on Structs

via Dev.toSomeB1oody

5.3.1. What Is a Method? Methods are similar to functions. They are also declared with the fn keyword, and they also have names, parameters, and return values. But methods are different from functions in a few ways: Methods are defined in the context of a struct (or an enum or a trait object). The first parameter of a method is always self , which represents the struct instance the method belongs to and is called on, similar to self in Python and this in JavaScript. 5.3.2. Practical Use of Methods Let’s continue with an example from the previous article: struct Rectangle { width : u32 , length : u32 , } fn main () { let rectangle = Rectangle { width : 30 , length : 50 , }; println! ( "{}" , area ( & rectangle )); } fn area ( dim : & Rectangle ) -> u32 { dim .width * dim .length } The area function calculates an area, but it is special: it only applies to rectangles, not to other shapes or other types. If we later add functions that calculate the areas of other shapes, the name area wil

Continue reading on Dev.to

Opens in a new tab

Read Full Article
0 views

Related Articles