gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:28:13 25 4
gpt4 key购买 nike

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

在下面的代码中,get正在作用于Vec<T>

fn first<T: PartialOrd + Copy>(list: Vec<T>) -> 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> (又名 &[T] ):

fn first<T: PartialOrd + Copy>(list: &Vec<T>) -> 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);
}

最佳答案

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

来自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 self. Given the receiver and name of a method, Rust can figure out definitively whether the method is reading (&self), mutating (&mut self), or consuming (self). 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
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com