英文:
implement Default for a templated struct where the only difference is the templated variable
问题
在定义了一个具有长度模板的矩阵之后,以便我可以更轻松地控制大小:
pub struct SquareMatrix<const length: usize> {
data: [[f32; length]; length],
}
我为该矩阵定义了默认函数:
impl Default for SquareMatrix<2> {
fn default() -> Self {
return SquareMatrix {
data: [[0.0; 2]; 2],
}
}
}
impl Default for SquareMatrix<3> {
fn default() -> Self {
return SquareMatrix {
data: [[0.0; 3]; 3],
}
}
}
impl Default for SquareMatrix<4> {
fn default() -> Self {
return SquareMatrix {
data: [[0.0; 4]; 4],
}
}
}
这看起来不够优雅,因为它们唯一的区别是模板的长度。但是,当我去掉length
并且只定义一个有模板的函数时:
impl Default for SquareMatrix<length> {
fn default() -> Self {
return SquareMatrix {
data: [[0.0; length]; length],
}
}
}
出现错误提示:length not found in this scope
是否有一种方法可以为模板结构定义一个模板函数?
英文:
After defining a matrix where the length templated so I can control the size easier:
pub struct SquareMatrix<const length: usize> {
data: [[f32; length]; length],
}
I define default functions for the matrix:
impl Default for SquareMatrix<2> {
fn default() -> Self {
return SquareMatrix {
data: [[0.0; 2];2],
}
}
}
impl Default for SquareMatrix<3> {
fn default() -> Self {
return SquareMatrix {
data: [[0.0; 3];3],
}
}
}
impl Default for SquareMatrix<4> {
fn default() -> Self {
return SquareMatrix {
data: [[0.0; 4];4],
}
}
}
It does not look elegant as the only difference of them is the length which is templated. But when I take out the length
and define only 1 templated function:
impl Default for SquareMatrix<length> {
fn default() -> Self {
return SquareMatrix {
data: [[0.0; length]; length],
}
}
}
Error prompt: length not found in this scope
Is there a way to define a templated function for templated struct?
答案1
得分: 3
你已经很接近了,你只需要在Default
实现中定义泛型参数:
#[derive(Debug)]
pub struct SquareMatrix<const LENGTH: usize> {
data: [[f32; LENGTH]; LENGTH],
}
impl<const LENGTH: usize> Default for SquareMatrix<LENGTH> {
fn default() -> Self {
return SquareMatrix {
data: [[0.0; LENGTH]; LENGTH],
};
}
}
fn main() {
let matrix: SquareMatrix<2> = Default::default();
println!("{:?}", matrix);
}
SquareMatrix { data: [[0.0, 0.0], [0.0, 0.0]] }
还有一点小问题:const泛型应该使用全大写字母表示。
英文:
You are close, you just need to define the generic in the Default
implementation:
#[derive(Debug)]
pub struct SquareMatrix<const LENGTH: usize> {
data: [[f32; LENGTH]; LENGTH],
}
impl<const LENGTH: usize> Default for SquareMatrix<LENGTH> {
fn default() -> Self {
return SquareMatrix {
data: [[0.0; LENGTH]; LENGTH],
};
}
}
fn main() {
let matrix: SquareMatrix<2> = Default::default();
println!("{:?}", matrix);
}
SquareMatrix { data: [[0.0, 0.0], [0.0, 0.0]] }
Also, minor nitpick: const generics should be written in all caps.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论