为什么 &v[1] + &v[2] 与 Rust 中的 v[1] + v[2] 具有相同的结果? [英] Why does &v[1] + &v[2] have the same result as v[1] + v[2] in Rust?

查看:46
本文介绍了为什么 &v[1] + &v[2] 与 Rust 中的 v[1] + v[2] 具有相同的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习所有权和借贷.

I'm learning about ownership and borrowing.

borrow1borrow2 的区别在于 &borrow2 中打印时的用法:

The difference between borrow1 and borrow2 is the usage of & while printing in borrow2:

fn borrow1(v: &Vec<i32>) {
    println!("{}", &v[10] + &v[12]);
}

fn borrow2(v: &Vec<i32>) {
    println!("{}", v[10] + v[12]);
}

fn main() {
    let mut v = Vec::new();

    for i in 1..1000 {
        v.push(i);
    }

    borrow1(&v);
    println!("still own v {} , {}", v[0], v[1]);

    borrow2(&v);
    println!("still own v {} , {}", v[0], v[1]);
}

为什么它们给出相同的输出,即使 borrow1 没有 &?

Why do they give the same output, even though borrow1 doesn't have &?

推荐答案

Vec 的索引运算符 ([]) 返回一个 T.在这种情况下,这是一个 i32.因此 v[0] 返回一个 i32&v[0] 返回一个 &i32:

The index operator ([]) for a Vec<T> returns a T. In this case, that's an i32. Thus v[0] returns an i32 and &v[0] returns an &i32:

let a: i32 = v[0];
let b: &i32 = &v[0];

v[0] 之所以有效,是因为 i32 实现了 复制.

v[0] only works because i32 implements Copy.

i32 已经为 (i32, i32)(&i32, &i32).这两个实现以相同的方式添加值,所以你得到相同的结果.

i32 has implemented Add for both the (left-hand side, right-hand-side) pairs of (i32, i32) and (&i32, &i32). The two implementations add values in the same way, so you get the same result.

另见:

这篇关于为什么 &amp;v[1] + &amp;v[2] 与 Rust 中的 v[1] + v[2] 具有相同的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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