为什么在使用粗箭头语法构建的哈希变量之前添加类型会导致类型检查失败错误?
Raku 是一种渐进打字语言。因此,下面的代码:
my %hash = abc => 4.5, abd => 5.5, bcd => 6.4, bce => 3.6;
与以下代码相同:
my Hash %hash = abc => 4.5, abd => 5.5, bcd => 6.4, bce => 3.6;
但是,它报告错误:
Type check failed in assignment to %hash; expected Hash but got Rat (4.5)
为什么在使用胖箭头语法构建的哈希变量之前添加类型会导致类型检查失败错误?
Raku is gradual typing language. So the code below:
my %hash = abc => 4.5, abd => 5.5, bcd => 6.4, bce => 3.6;
is the same as:
my Hash %hash = abc => 4.5, abd => 5.5, bcd => 6.4, bce => 3.6;
However, it reports an error:
Type check failed in assignment to %hash; expected Hash but got Rat (4.5)
Why adding a type before a hash variable that build with fat arrow syntax leaded to type check failed error?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您说
my Hash %hash
时,您指定的Hash
仅将Hash
作为值 。在您的示例中,您将Rat
作为值放入哈希中,而不是Hash
es。这就是错误消息试图告诉您的内容。您的示例会这样更有意义:
您强制所有值为
数字
。另一种写法是:
第一种方法只是第二种方法的语法糖。
如果您还想要限制键,还有两种方法可以实现:
将键限制为
Str
。请注意,默认情况下,类型为Str()
,又名:强制任何内容到Str
,这是不相同。更语法糖化的方式是:
我认为,更具可读性,因为很清楚按键的输入是什么。
When you say
my Hash %hash
, you're specifying aHash
that will only takeHash
as a value. And in your example, you're puttingRat
s into the hash as values, notHash
es. Which is what the error message is trying to tell you.Your example would make more sense this way:
in which you force all values to be
Numeric
.Another way of writing that, is:
The first way is just syntactic sugar for the second.
If you also want to limit the keys, there are also two ways to do that:
would limit the keys to
Str
. Note that by default, the type isStr()
, aka: coerce anything toStr
, which is not the same.The more syntactic sugary way is:
which I think, is more readable as it is clear what the typing of the keys is.