gpt4 book ai didi

rust - 在二维数组中赋值

转载 作者:行者123 更新时间:2023-11-29 07:52:57 24 4
gpt4 key购买 nike

我正在用 Rust 编写一些代码(主要作为 POC)。该代码采用一个二维数组,将其传递给第二个函数以执行一些矩阵数学运算(我知道有一个标准库可以执行此操作,但我想习惯它的工作原理)。

问题是二维数组的赋值导致了问题。

我的代码是这样的

fn main() 
{
// first create a couple of arrays - these will be used
// for the vectors
let line1: [i32; 4] = [4, 2, 3, 3];
let line2: [i32; 4] = [3, 4, 5, 7];
let line3: [i32; 4] = [2, 9, 6, 2];
let line4: [i32; 4] = [5, 7, 2, 4];

// create two holding arrays and assign
let array_one = [line1, line3, line4, line2];
let array_two = [line2, line1, line3, line4];

// let's do the multiply
let result = matrix_multiply(&array_one, &array_two);
println!("{:?}", result);
}

fn matrix_multiply(vec1:&[&[i32;4];4], vec2:&[&[i32;4];4]) -> [[i32; 4];4]
{
// we need to deference the parameters passed in
let vec_one:[[i32;4];4] = vec1;
let vec_two:[[i32;4];4] = vec2;

// we need to store the sum
let mut sum = 0;

// we need to create the arrays to put the results into
let mut result = [[0i32; 4]; 4];

// loop through the two vectors
for vone in 0..4
{
for vtwo in 0..4
{
for k in 0..4
{
sum = sum + vec1[[vone].k] * vec2[[k].vtwo];
}
result[[vec_one].vec_two] = sum;
sum = 0;
}
}

return result;
}

我也尝试过 result[vec_o​​ne][vec_two] = sum 但是当我开始编译时,似乎分配给数组时出现问题。

我在这里做错了什么?

最佳答案

这是你的错误,我相信(至少其中之一):

<anon>:15:34: 15:44 error: mismatched types:
expected `&[&[i32; 4]; 4]`,
found `&[[i32; 4]; 4]`
(expected &-ptr,
found array of 4 elements) [E0308]
<anon>:15 let result = matrix_multiply(&array_one, &array_two);
^~~~~~~~~~

问题是,数组的引用或取消引用不能在其嵌套的多个级别上进行。这是因为 [&[i32; 的内存布局。 4]; 4][[i32; 4]; 4] 在内容和大小上都完全不同——前一个数组由四个指向其他数组的指针组成(总共 4*4=16/8*4=32 字节,具体取决于您机器的体系结构),而后者由四个顺序排列的数组组成(总共 4*4*4=64 字节)。根本没有办法从 [[i32; 4]; 4]&[&[i32; 4]; 4] 无需重建外部数组,Rust 永远不会为你做,因为它太神奇了。

你真的不需要使用内部引用;事实上,您甚至可能根本不需要通过引用传递这些数组:Copy 类型的数组也是Copy,因此您可以通过值传递它们。它们足够小,不会造成任何性能影响,并且编译器可能会自动优化它:

fn main()  {
// first create a couple of arrays - these will be used
// for the vectors
let line1: [i32; 4] = [4, 2, 3, 3];
let line2: [i32; 4] = [3, 4, 5, 7];
let line3: [i32; 4] = [2, 9, 6, 2];
let line4: [i32; 4] = [5, 7, 2, 4];

// create two holding arrays and assign
let array_one = [line1, line3, line4, line2];
let array_two = [line2, line1, line3, line4];

// let's do the multiply
let result = matrix_multiply(array_one, array_two);
println!("{:?}", result);
}

fn matrix_multiply(vec1: [[i32; 4]; 4], vec2: [[i32; 4]; 4]) -> [[i32; 4]; 4] {
// we need to create the arrays to put the results into
let mut result = [[0i32; 4]; 4];

// loop through the two vectors
for vone in 0..4 {
for vtwo in 0..4 {
let mut sum = 0;
for k in 0..4 {
sum += vec1[vone][k] * vec2[k][vtwo];
}
result[vone][vtwo] = sum;
}
}

result
}

(试一试 here )

我还根据当前的社区惯例(大括号定位、间距等)使您的代码更加地道,并且修复了访问数组的奇怪语法。

关于rust - 在二维数组中赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33145748/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com