可以使用关联常量来初始化固定大小数组的长度吗? [英] Can associated constants be used to initialize the length of fixed size arrays?

查看:30
本文介绍了可以使用关联常量来初始化固定大小数组的长度吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C++ 中,您可以在模板中传递积分

In C++, you have the ability to pass integrals inside templates

std::array<int, 3> arr; //fixed size array of 3

我知道 Rust 已经内置了对此的支持,但是如果我想创建类似线性代数向量库的东西怎么办?

I know that Rust has built in support for this, but what if I wanted to create something like linear algebra vector library?

struct Vec<T, size: usize> {
    data: [T; size],
}

type Vec3f = Vec<f32, 3>;
type Vec4f = Vec<f32, 4>;

这就是我目前在 D 中所做的.我听说 Rust 现在有 相关常数.

This is currently what I do in D. I have heard that Rust now has Associated Constants.

我已经很长时间没有使用 Rust 了,但这似乎根本没有解决这个问题,或者我错过了什么?

I haven't used Rust in a long time but this doesn't seem to address this problem at all or have I missed something?

据我所知,关联常量仅在特征中可用,这意味着我仍然需要手动创建 N 向量类型.

As far as I can see, associated constants are only available in traits and that would mean I would still have to create N vector types by hand.

推荐答案

不,关联的常量没有帮助也不打算.相关的任何东西都是输出,而问题中的用例需要输入.原则上可以从类型参数和具有关联常量的 trait 构造一些东西(至少,只要你可以使用类型参数的关联常量——遗憾的是,这还行不通).但这具有糟糕的人体工程学,并不比 typenum 之类的现有黑客好多少.

No, associated constants don't help and aren't intended to. Associated anything are outputs while use cases such as the one in the question want inputs. One could in principle construct something out of type parameters and a trait with associated constants (at least, as soon as you can use associated constants of type parameters — sadly that doesn't work yet). But that has terrible ergonomics, not much better than existing hacks like typenum.

非常需要整数类型参数,因为正如您所注意到的,它们可以实现许多在当前 Rust 中并不真正可行的事情.人们谈论并计划,但事实并非如此到了.

Integer type parameters are highly desired since, as you noticed, they enable numerous things that aren't really feasible in current Rust. People talk about this and plan for it but it's not there yet.

这篇关于可以使用关联常量来初始化固定大小数组的长度吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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