Skip to content

Instantly share code, notes, and snippets.

@oylenshpeegul
Last active Oct 18, 2022
Embed
What would you like to do?
The from-perl-to-rust Traits page using Object::Pad
#!/usr/bin/env perl
# Would it be worth replacing this Perl code?
# https://oylenshpeegul.gitlab.io/from-perl-to-rust/traits.html
use v5.32;
use Object::Pad;
role Area {
requires area;
}
class Circle implements Area {
has $radius :param = 0;
method area () {
3.14159265358979 * $radius ** 2
}
}
class Rectangle implements Area {
has $length :param = 0;
has $width :param = 0;
method area () {
$length * $width
}
}
my $c = Circle->new(radius => 1);
say "Area of circle is ", $c->area;
my $r = Rectangle->new(length => 2, width => 3);
say "Area of rectangle is ", $r->area;
@leonerd
Copy link

leonerd commented Oct 18, 2022

A small note here: To remain compatible with the upcoming core syntax version of this, you probably want to use field instead of has. And field takes a block expression rather than an immediate one there:

field $radius :param { 0 };

@oylenshpeegul
Copy link
Author

oylenshpeegul commented Oct 18, 2022

Thanks. I also changed requires to method and implements to :does, as suggested by Object::Pad 0.68. It warns that "field initialiser expression is experimental and may be changed or removed without notice" (even with no warnings 'experimental';), but presumably that's temporary.

#!/usr/bin/env perl

# Would it be worth replacing this Perl code?
# https://oylenshpeegul.gitlab.io/from-perl-to-rust/traits.html

use v5.36;
use Object::Pad;

role Area {
    method area;
}

class Circle :does(Area) {
    field $radius :param { 0 };

    method area () {
        3.14159265358979 * $radius ** 2
    }
}

class Rectangle :does(Area) {
    field $length :param { 0 };
    field $width :param { 0 };

    method area () {
        $length * $width
    }
}

my $c = Circle->new(radius => 1);
say "Area of circle is ", $c->area;

my $r = Rectangle->new(length => 2, width => 3);
say "Area of rectangle is ", $r->area;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment