gpt4 book ai didi

raku - 如何将类属性声明为类名的联合?

转载 作者:行者123 更新时间:2023-12-05 00:38:01 26 4
gpt4 key购买 nike

我正在阅读电子表格以寻找不同的结构。当我尝试使用 Moose 进行以下操作时,它似乎可以满足我的要求。我可以创建不同类型的对象,将其分配给找到的成员并转储 Cell 实例以供审查。

package Cell
{
use Moose;
use Moose::Util::TypeConstraints;
use namespace::autoclean;

has 'str_val' => ( is => 'ro', isa => 'Str', required => 1 );
has 'x_id' => ( is => 'ro', isa => 'Str', ); # later required => 1 );
has 'color' => ( is => 'ro', isa => 'Str', );
has 'border' => ( is => 'ro', isa => 'Str', );
has 'found' => ( is => 'rw', isa => 'Sch_Symbol|Chip_Symbol|Net', );
1;
}

如果我尝试在 Perl 6 中做同样的事情,它会编译失败。

class Cell {
has Str $.str_val is required;
has Str $.x_id is required;
has Str $.color;
has Str $.border;
has Sch_Symbol|Chip_Symbol|Net $.found is rw
}
Malformed has
at C:\Users\Johan\Documents/moose_sch_3.pl6:38
------> has Sch_Symbol'<'HERE'>'|Chip_Symbol|Net $.found is rw

我如何在 Perl 6 中执行此操作?

最佳答案

您可能希望他们担任共同角色并将其指定为类型

role Common {}
class Sch-Symbol does Common {…}


class Cell {

has Common $.found is rw;
}

或者你将不得不使用一个where约束

class Cell {

has $.found is rw where Sch-Symbol|Chip-Symbol|Net;
}

您还可以创建一个子集来包装 where 约束。

subset Common of Any where Sch-Symbol|Chip-Symbol|Net;

class Cell {

has Common $.found is rw;
}

请注意,where 约束比使用普通角色要慢。

关于raku - 如何将类属性声明为类名的联合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59970066/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com