什么是 <-
Rust 中的运算符/表达式?你可以找到the symbol here .
我碰巧在看一个描述 Rust 中的表达式和操作的页面。我不会用 Rust 编程,所以我问了一个亲 Rust 的 friend 这个符号是什么,但他也不知道它是什么。
最佳答案
<-
运算符不是稳定版 Rust 的一部分。至少现在还没有。
有一个RFC它提出了涉及 <-
的语法用于将新对象直接写入内存中的特定位置,作为 another RFC 的替代方案,建议 in
.这是(目前不稳定)box
的概括语法,它允许您直接分配到堆,而无需临时堆栈分配。
目前,如果不使用 unsafe
就无法做到这一点代码,通常你需要先在堆栈上分配。 this RFC 中有对潜在问题的讨论。这是相关 RFC 链中的第一个,并给出了背景动机,但关键原因是:
- 使用需要将对象写入特定内存地址的硬件。您现在可以在 Rust 中不安全地执行此操作,但如果 SDK 可以为此提供安全且高性能的 API,那就更好了。
- 直接写入堆的预分配部分比每次都分配新内存更快。
- 为新对象分配内存时,直接在堆上分配内存比先在堆栈上分配然后克隆或移动要快。
在 C++ 中,有一个称为“placement new”的功能,它通过让您向 new
提供一个参数来实现这一点。 , 这是开始写入的现有指针。例如:
// For comparison, a "normal new", allocating on the heap
string *foo = new string("foo");
// Allocate a buffer
char *buffer = new char[100];
// Allocate a new string starting at the beginning of the buffer
string *bar = new (buffer) string("bar");
据我所知,上面的 C++ 示例在带有 <-
的 Rust 中可能看起来像这样:
// Memory allocated on heap (with temporary stack allocation in the process)
let foo = Box::new(*b"foo");
// Or, without the stack allocation, when box syntax stabilises:
let foo = box *b"foo";
// Allocate a buffer
let mut buffer = box [0u8; 100];
// Allocate a new bytestring starting at the beginning of the buffer
let bar = buffer[0..3] <- b"bar";
我不希望这个精确代码按原样编译,即使实现了放置功能。但请注意,目前在 Rust 中不可能执行最后一行试图执行的操作:分配 b"bar"
直接在缓冲区的开头,而不是先在堆栈上分配。目前在 Rust 中,还没有办法做到这一点。连unsafe
代码在这里对你没有帮助。您仍然必须先在堆栈上分配,然后将其克隆到缓冲区:
// Note that b"bar" is allocated first on the stack before being copied
// into the buffer
buffer[0..3].clone_from_slice(&b"bar"[0..3]);
let bar = &buffer[0..3];
和box
语法在这里也无济于事。这将分配新的堆内存,然后您仍然必须将数据复制到缓冲区。
对于在堆上分配新对象时避免临时堆栈分配的更简单的情况,box
语法稳定后会解决这个问题。 Rust 在未来的某个时候需要解决更复杂的情况,但目前还不确定 <-
是将出现的语法。
关于syntax - Rust 中的 <- 符号是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49762055/