sách gpt4 ai đã đi

rust - 为什么 `get` 对 std::vec::Vec 和 &std::vec::Vec 都有效?

In lại 作者:行者123 更新时间:2023-12-03 11:28:13 25 4
mua khóa gpt4 Nike

我很困惑为什么这个函数 lấy适用于 Vec&Vec 。我知道&Vec自动转换为&[T]所以从某种意义上说,问题是为什么它适用于 Veccũng như &[T] 。显然,lấy&[T]一起工作,那么对于 Vec 是否单独实现除了 &[T] 的实现之外?看文档,好像不是,只有一个lấyhoàn thành:https://doc.rust-lang.org/std/vec/struct.Vec.html#method.get

在下面的代码中,lấy正在作用于Vec .

fn first(list: Vec) -> T {
*list.get(0).unwrap()
}

fn main() {
let number_list = vec![34, 50, 25, 100, 65];
let result = first(number_list);
println!("The first number is {}", result);
}

在此代码中,它作用于 &Vec (又名 &[T] ):

fn first(list: &Vec) -> T {
*list.get(0).unwrap()
}

fn main() {
let number_list = vec![34, 50, 25, 100, 65];
let result = first(&number_list);
println!("The first number is {}", result);
}

1 Câu trả lời

这是由于自动引用造成的。

TừMethod Syntax在《Rust 编程语言》中...

Rust has a feature called automatic referencing and dereferencing [...] when you call a method with object.something(), Rust automatically adds in &, &mut, or * so object matches the signature of the method. In other words, the following are the same:

p1.distance(&p2);
(&p1).distance(&p2);

The first one looks much cleaner. This automatic referencing behavior works because methods have a clear receiver—the type of bản thân. Given the receiver and name of a method, Rust can figure out definitively whether the method is reading (&self), mutating (&mut self), or consuming (bản thân). The fact that Rust makes borrowing implicit for method receivers is a big part of making ownership ergonomic in practice.

关于rust - 为什么 `get` 对 std::vec::Vec 和 &std::vec::Vec 都有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62225239/

25 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com