- Learning Rust
- Paul Johnson Vesa Kaihlavirta
- 401字
- 2021-07-02 23:07:20
A practical example
In the example code, matrix, we can see how to use a 2D array and how to pass by a reference, with the receiving function calculating the result of a matrix multiplication. Let's examine the code:
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 // we are creating an array of references let array_one = [&line1, &line3, &line4, &line2]; let array_two = [&line2, &line1, &line3, &line4]; // let's do the multiply // we are passing in a ref array containing ref arrays 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 }
When compiled, you will get the following output:

What we need to really consider here is the definition line for the matrix_multiply function:
fn matrix_multiply(vec1: &[&[i32;4];4], vec2: &[&[i32;4];4]) -> [[i32; 4];4]
If you recall how we told a function the name of the variable and the type earlier, we said it was variable_name: variable_type. The preceding line may look very much different, but it really isn't:

We are passing in a reference to a holding array, which holds references to other arrays. The array is defined using [i32;4]; therefore, the reference is &[i32;4]. This is the inner array. The outer array [i32;4] is also a reference (&[i32;4]), which has a size of 4. Therefore, when we put these together, we have the following:

The preceding example shows how to pass by a reference quite nicely, though in reality, it is most likely that the compiler will optimize this out to something faster for such a small data sample. It does show, however, how it's done.
The golden rule is that what you send over to the function has to marry up with what the function is expecting.
- R語(yǔ)言數(shù)據(jù)分析從入門(mén)到精通
- Moodle Administration Essentials
- Mastering LibGDX Game Development
- PostgreSQL 11從入門(mén)到精通(視頻教學(xué)版)
- 深度學(xué)習(xí):算法入門(mén)與Keras編程實(shí)踐
- 概率成形編碼調(diào)制技術(shù)理論及應(yīng)用
- Python Data Analysis Cookbook
- Node.js全程實(shí)例
- Nginx實(shí)戰(zhàn):基于Lua語(yǔ)言的配置、開(kāi)發(fā)與架構(gòu)詳解
- Visual Basic程序設(shè)計(jì)實(shí)驗(yàn)指導(dǎo)(第二版)
- Getting Started with Python
- 零基礎(chǔ)看圖學(xué)ScratchJr:少兒趣味編程(全彩大字版)
- Visual Basic 程序設(shè)計(jì)實(shí)踐教程
- Java EE項(xiàng)目應(yīng)用開(kāi)發(fā)
- JavaScript程序設(shè)計(jì)實(shí)例教程(第2版)