为什么 Rust 既有按值调用又有按引用调用? [英] Why does Rust have both call by value and call by reference?

查看:44
本文介绍了为什么 Rust 既有按值调用又有按引用调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有些语言,比如 Haskell,不区分值传递和引用传递.然后,编译器可以通过启发式方法大致选择最有效的调用约定.一个启发式示例适用于 Linux x64 ABI:如果参数的大小大于 16 字节,则传递一个指向堆栈的指针,否则传递寄存器中的值.

Some languages, like Haskell, make no distinction between pass-by-value and pass-by-reference. The compiler can then approximately choose the most efficient calling convention with a heuristic. One example heuristic would be for the Linux x64 ABI: if the size of parameter is greater than 16 bytes, pass a pointer to the stack otherwise pass the value in registers.

在 Rust 中保留按值传递和按引用传递(当然是不可变的)的概念并强制用户选择有什么好处?

What is the advantage of keeping both notions of pass-by-value and pass-by-reference (non-mutable of course) in Rust and forcing the user to choose?

如果看到值被修改,会不会是传值是传引用+复制的语法糖?

Could it be the case that pass-by-value is syntactic sugar for pass-by-reference + copy if the value is seen to be modified?

推荐答案

两件事:

  1. Rust 将基于类似的启发式将某些按值传递调用转换为按引用传递.
  2. 传值表示所有权转移,传引用表示借用.这些非常不同,并且与您所询问的 asm 级别的问题完全正交.

换句话说,在 Rust 中,这两种形式具有不同的语义.不过,这并不排除进行优化.

In other words, in Rust, these two forms have different semantics. That doesn't preclude also doing the optimization, though.

这篇关于为什么 Rust 既有按值调用又有按引用调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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