Methods
In Rust, we don't have classes or inheritance, but we can attach methods to structs and enums. This looks an awful lot like object-oriented Perl. Say we had a rectangle object that knew how to find its own area. In Perl, we might write something like this.
#!/usr/bin/env perl
use v5.28;
use warnings;
use experimental qw(signatures);
package Rectangle {
sub new($class, $length, $width) {
my $self = {
_length => $length,
_width => $width,
};
bless $self, $class;
return $self;
}
sub area($self) {
$self->{_length} * $self->{_width}
}
}
my $r = Rectangle->new(2, 3);
say "Area is ", $r->area;
In Rust, we'd create a Rectangle struct first and then separately implement new
and area
methods for that struct in an impl
block. We use a dot (.
) in Rust where we use an arrow (->
) in Perl, but otherwise it looks the same.
struct Rectangle { length: f64, width: f64, } impl Rectangle { fn new(length: f64, width: f64) -> Self { Self{length, width} } fn area(&self) -> f64 { self.length * self.width } } fn main() { let r = Rectangle::new(2.0, 3.0); println!("Area is {}", r.area()); }
Indeed, in both Rust and Perl, these method calls are just sugar for function calls. That is, just as in Perl, these two are the same
say "Area is ", $r->area;
say "Area is ", Rectangle::area($r);
in Rust, these two are the same.
#![allow(unused_variables)] fn main() { println!("Area is {}", r.area()); println!("Area is {}", Rectangle::area(&r)); }