为什么在使用粗箭头语法构建的哈希变量之前添加类型会导致类型检查失败错误?

发布于 2025-01-09 15:45:16 字数 502 浏览 0 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

情魔剑神 2025-01-16 15:45:16

当您说my Hash %hash时,您指定的Hash仅将Hash作为 。在您的示例中,您将 Rat 作为值放入哈希中,而不是 Hashes。这就是错误消息试图告诉您的内容。

您的示例会这样更有意义:

my Numeric %hash = abc => 4.5, abd => 5.5, bcd => 6.4, bce => 3.6;

您强制所有数字

另一种写法是:

my %hash is Hash[Numeric] = abc => 4.5, abd => 5.5, bcd => 6.4, bce => 3.6;

第一种方法只是第二种方法的语法糖。

如果您想要限制键,还有两种方法可以实现:

my %hash is Hash[Numeric,Str] = abc => 4.5, abd => 5.5, bcd => 6.4, bce => 3.6;

将键限制为Str。请注意,默认情况下,类型为 Str(),又名:强制任何内容到 Str,这是相同。

更语法糖化的方式是:

my Numeric %hash{Str} = abc => 4.5, abd => 5.5, bcd => 6.4, bce => 3.6;

我认为,更具可读性,因为很清楚按键的输入是什么。

When you say my Hash %hash, you're specifying a Hash that will only take Hash as a value. And in your example, you're putting Rats into the hash as values, not Hashes. Which is what the error message is trying to tell you.

Your example would make more sense this way:

my Numeric %hash = abc => 4.5, abd => 5.5, bcd => 6.4, bce => 3.6;

in which you force all values to be Numeric.

Another way of writing that, is:

my %hash is Hash[Numeric] = abc => 4.5, abd => 5.5, bcd => 6.4, bce => 3.6;

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:

my %hash is Hash[Numeric,Str] = abc => 4.5, abd => 5.5, bcd => 6.4, bce => 3.6;

would limit the keys to Str. Note that by default, the type is Str(), aka: coerce anything to Str, which is not the same.

The more syntactic sugary way is:

my Numeric %hash{Str} = abc => 4.5, abd => 5.5, bcd => 6.4, bce => 3.6;

which I think, is more readable as it is clear what the typing of the keys is.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文