可以在 Rust 中推断数组长度吗? [英] Can array lengths be inferred in Rust?

查看:63
本文介绍了可以在 Rust 中推断数组长度吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以这样做:

let a: [f32; 3] = [0.0, 1.0, 2.0];

但是为什么这不起作用?

But why doesn't this work?

let a: [f32; _] = [0.0, 1.0, 2.0];

在我看来,长度是多余的,推断起来很琐碎.有没有办法避免必须明确指定它?(并且不必将 f32 附加到所有文字.)

It seems to me that the length is redundant and trivial to infer. Is there a way to avoid having to specify it explicitly? (And without having to append f32 to all the literals.)

推荐答案

_ 只能在两种情况下使用:在模式中,匹配要忽略的值,以及作为类型的占位符.在数组类型中,长度不是类型,而是表达式,_不能在表达式中使用.

_ can only be used in two contexts: in patterns, to match a value to ignore, and as a placeholder for a type. In array types, the length is not a type, but an expression, and _ cannot be used in expressions.

不过,您可以做的是仅将 f32 附加到其中一个文字并完全省略类型.由于数组的所有项必须具有相同的类型,因此编译器将推断数组的正确元素类型.

What you can do, though, is append f32 to only one of the literals and omit the type completely. Since all the items of an array must have the same type, the compiler will infer the correct element type for the array.

let a = [0.0f32, 1.0, 2.0];

这篇关于可以在 Rust 中推断数组长度吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆