作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
Perl6/乐库
我想创建一个子,只允许将某些值传递给它。并且不传递允许的值将产生检查器错误(perl6 -c)。
我该怎么做呢?
非常感谢,
-T
嗨,雷夫,
在我的 WinPopUps 模块中,我使用了“where”方法,因为它一目了然地告诉用户允许的值是什么。我喜欢它!一切都与可维护性有关! (对了,下面是你创造的怪物!)
sub WinPopUp( Str $TitleStr,
Str $MessageStr,
Str $Icons where * ~~ "Exclamation" |
"Warning" |
"Information" |
"Asterisk" |
"Question" |
"Stop" |
"Error" |
"Hand",
Str $Buttons where * ~~ "AbortRetryIgnore" |
"CancelTryAgainContinue" |
"Help" |
"Ok" |
"OkCancel" |
"RetryCancel" |
"YesNo" |
"YesNoCancel" )
is export( :WinPopUp ) {
最佳答案
您可以简单地添加 where
值的条件
sub foo( Int $binary where * ~~ 0|1 ) { ... }
where
条件可以是任意代码块(甚至是我相信的子代码块)。
subset
.
subset BinaryInt of Int where * ~~ 0|1;
sub foo( BinaryInt $binary ) { ... }
my BinaryInt $i = 0;
$i++;
$i++;
# -> Type check failed in assignment to $i; expected BinaryInt but got Int (2)
subset FalseBinaryInt of BinaryInt where not *;
my FalseBinaryInt $i = 0;
$i++;
# -> Type check failed in assignment to $i; expected FalseBinaryInt but got Int (1)
sub WinPopUp( Str $TitleStr,
Str $MessageStr,
MessageBoxIcons $Icons where * ~~ Exclamation |
Information |
...
enum MessageBoxIcons is export {
Exclamation => 0x00000030,
Information => 0x00000040,
...
}
MessageBoxW
的值。 (我假设这就是你正在做的事情)。
MessageBoxW
,我会调用你的子
message-box
(在 Raku 中,我们倾向于将 CamelCase 仅用于类和类型等)只是为了与
MessageBoxW
保持一致。
关于raku - perl6/乐库 : how to I restrict the values allowed in a variable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59222421/
我是一名优秀的程序员,十分优秀!