[英]Rust: How can a reference be a type?
So what I am asking is, what is the difference between the return types, &std::vec::Vec and std::vec::Vec?所以我要问的是,返回类型 &std::vec::Vec 和 std::vec::Vec 之间有什么区别? Just curious.
只是好奇。 If I make a reference to something, I'm not creating a new type.
如果我引用某些东西,我不是在创建新类型。 It still retains its data and structure and so retains its type.
它仍然保留其数据和结构,因此保留其类型。 But for some reason I get this error:
但由于某种原因,我收到此错误:
error[E0308]: mismatched types
--> src/cam.rs:170:3
|
168 | pub fn index2d(self, x: usize, y: usize) -> Vec<u8> {
| ------- expected `std::vec::Vec<u8>` because of return type
169 | let c = &self.pyxels[y*WIDTH+x];
170 | c
| ^
| |
| expected struct `std::vec::Vec`, found reference
| help: try using a conversion method: `c.to_vec()`
|
= note: expected type `std::vec::Vec<u8>`
found type `&std::vec::Vec<u8>`
^ (umm excuse me?)
That one little symbol (&) really seems to make all the difference and I have no clue why.那个小符号 (&) 似乎真的很重要,我不知道为什么。
If I make a reference to something, I'm not creating a new type.
如果我引用某些东西,我不是在创建新类型。
If by "creating a new type" , you mean "creating an object of a different type" , then yes, that's exactly what you're doing.如果“创建新类型”的意思是“创建不同类型的对象” ,那么是的,这正是您正在做的。 A reference to a thing is not that thing.
对事物的引用不是那个事物。 It's similar to the difference between having a house, and having a slip of paper with the address of a house written on it.
这类似于有房子和有一张写有房子地址的纸条之间的区别。
Though the syntax of Rust often makes access to an object through a reference look identical to direct access to that object.尽管 Rust 的语法通常使通过引用访问对象看起来与直接访问该对象相同。
let v: Vec<u8> = Vec::new();
let vr = &v;
assert_eq!(v.len(), rv.len());
So perhaps that is why you are confused?所以也许这就是你困惑的原因?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.