rust中,“借用”是指针吗?而拥有所有权的变量是变量变身?

rust这种语言粗略学了一下,跟之前学的语言有不少区别。举个例子:
https://www.zhihu.com/answer/...
上面那篇文章里面提到把变量的所有权传递给hashMap时,是把变量本身传递到hashMap,比如String本身,而不是&str(引用)。那传递变量本身时,是值复制吗?就是把整个变量都复制一份给HashMap?假如这个变量是一个很大的struct,岂不是浪费大量的内存?

阅读 1.7k
2 个回答

References and Borrowing

fn main() {
    let s1 = String::from("hello");

    let len = calculate_length(&s1);

    println!("The length of '{}' is {}.", s1, len);
}

fn calculate_length(s: &String) -> usize {
    s.len()
}

上面calculate_length中使用&String就是一个references, 也就是 reference borrowing,

We call the action of creating a reference borrowing. As in real life, if a person owns something, you can borrow it from them. When you’re done, you have to give it back. You don’t own it.

Reference VS Pointer

A reference is like a pointer in that it’s an address we can follow to access the data stored at that address; that data is owned by some other variable. Unlike a pointer, a reference is guaranteed to point to a valid value of a particular type for the life of that reference.

除此之外 Reference 与 Pointer 之前是可以转换的

数据之间的交换方式 - Move

 let s1 = String::from("hello");

下面是内存分布局:
https://doc.rust-lang.org/stable/book/img/trpl04-01.svg

其中s1的数据结构是存放在栈上,ptr指向的实际是堆地址;

当执行下面语句之后的内存布局:

 let s2 = s1;

此时s1已无效,也就是不能访问了; 这是Move语意

数据之间的交换方式 - Clone

在上面执行 let s1 = String::from("hello");之后如果再执行下面代码:

 let s2 = s1.clone();

内存布局就是这样的:

这是Clone

数据之间的交换方式 - Copy(Stack-Only Data)

首先注意只有栈上的数据才能有Copy,并且实现了Copy trait,当实现Copy trait之后这个值再赋给其他变量之后仍然可以使用.

  let x = 5;
  let y = x;
  println!("x = {}, y = {}", x, y);

上面x是integer类型并且实现了Copy trait,所以在赋给y后仍然可用

实现Copy trait的基本类型:

  • All the integer types, such as u32.
  • The Boolean type, bool, with values true and false.
  • All the floating point types, such as f64.
  • The character type, char.
  • Tuples, if they only contain types that also implement Copy. For example, (i32, i32) implements Copy, but (i32, String) does not.

what-is-ownership

"借用" 不是指针,它是用于引用。(Rust 有指针类型的)

所有权传递不是借用,也不需要拷贝。拷贝需要显式调用 clone 。(除非是简单类型,即实现了 Copy trait 的类型)

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进