In Rust, classes are not a native feature. Instead, you can use structs and implement methods for them using the impl
block. Here's an example of how to create a struct and add methods to it:
main.rs914 chars35 lines
In this example, we defined a Rectangle
struct with width
and height
fields. Then, inside an impl
block, we implemented several methods for that struct. We have a method to calculate the area of the rectangle, a method to determine if the rectangle can fit inside another rectangle, and a static method to create a new rectangle with the specified width and height.
Finally, in the main
function, we created two Rectangle
instances using the create
method and the struct literal syntax. Then, we printed the area of the first rectangle and determined if it can fit inside the second rectangle using the can_fit_inside
method.
gistlibby LogSnag