我可以只使用类型而不是具体变量来获取Rust数组的长度吗? [英] Can I get a Rust array's length with only a type, not a concrete variable?

查看:47
本文介绍了我可以只使用类型而不是具体变量来获取Rust数组的长度吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将以下C ++代码重写为Rust:

I want to rewrite the following C++ code into Rust:

using storage = array<int, 3>;
const size_t storage_len = sizeof(storage) / sizeof(storage::value_type);

如何在没有具体变量的情况下获得恒定长度的值?

How can I get that constant length value without a concrete variable?

出于动机,尽管看似微不足道,但我想在不声明变量的情况下打印数组的元素计数.我知道我可以使用一个常量值或声明一个虚拟变量,但是我不知道Rust如何保存C ++代码.

As motivation, although it may seem trivial, I want to print the array's element count without declaring a variable. I know I could use a constant value or declare a dummy variable, but I wonder how Rust can preserve C++ code.

我承认没有具体变量的 尚不清楚.我想实现上述C ++功能,但是这种解释可能会引起误解.我很好奇是否有任何方法可以获取数组的元素类型.

I admit without a concrete variable is not clear. I want to achieve the above C++ feature, but this explanation can be misleading. I'm curious if there is any way to get the array's element type.

推荐答案

Rust现在支持const泛型.我留下了原来的答案,所以人们知道为什么有人会首先问这个问题.

Rust now has support for const generics. I left the old answer so people have an idea why someone might have asked this in the first place.

自Rust 1.51以来的新答案:

pub trait Length {
    const LEN: usize;
}

impl<T, const LENGTH: usize> Length for [T; LENGTH] {
    const LEN: usize = LENGTH;
}

旧答案:

我知道您只想从类型信息中检索数组长度.Rust没有内置的PI类型(也就是 const泛型).这意味着该语言当前不支持 not 类型的通用参数(例如数组长度的整数).

I understand that you want to retrieve the array length from the type information alone. Rust does not have built-in PI types (a.k.a. const generics). This means generic parameters which are not types (like an integer for an array length) are currently not supported by the language.

跟踪此问题,我们很可能会获得支持为此,尽管不是在不久的将来.

There is an issue tracking this and we are likely to see support for it in the future, though not the near future.

如果有必要,可以通过为每种类型实现特征来解决该限制:

If you have to, you can work around that limitation by implementing a trait for each type:

trait GetLength {
    fn len() -> usize;
}

impl<T> GetLength for [T; 0] {
    fn len() -> usize {
        0
    }
}

impl<T> GetLength for [T; 1] {
    fn len() -> usize {
        1
    }
}

// ...

fn main() {
    println!("{}", <[String; 1]>::len());
}

宏可以帮助防止重复输入:

Macros can help prevent repetitive typing:

trait GetLength {
    fn len() -> usize;
}

macro_rules! impl_get_length {
    ($v:expr) => {
        impl<T> GetLength for [T; $v] {
            fn len() -> usize {
                $v
            }
        }
    };
}

impl_get_length!{ 0 }
impl_get_length!{ 1 }

// ...

fn main() {
    println!("{}", <[String; 1]>::len());
}

typenum 之类的板条箱也有助于为const泛型提供一些支持在现有语言范围内.

Crates like typenum also help to provide some support for const generics within the existing language.

这篇关于我可以只使用类型而不是具体变量来获取Rust数组的长度吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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