Last active
October 18, 2022 12:30
-
-
Save oylenshpeegul/52102a73fca1c650531f250bae01cb2a to your computer and use it in GitHub Desktop.
The from-perl-to-rust Traits page using Object::Pad
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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; |
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
A small note here: To remain compatible with the upcoming core syntax version of this, you probably want to use
field
instead ofhas
. Andfield
takes a block expression rather than an immediate one there: