簡體   English   中英

Rust - String::from() 實際上是如何工作的?

[英]Rust - How does String::from() actually work?

我還是 rust 的新手,所以有一些關於它的東西我仍然不知道

我正在嘗試拆分一個String值並將其傳遞給一個變量,如下所示:

let mut splitted_line = String::from("something=random").split("=");
let key = splitted_line.nth(0).expect("incorrect line format");
let value = splitted_line.nth(1).expect("incorrect line format");

上面的代碼引發以下錯誤:

error[E0716]: temporary value dropped while borrowed
  --> src\main.rs:49:37
   |
49 |             let mut splitted_line = String::from("something=random").split("=");
   |                                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^           - temporary value is freed at the end of this statement
   |                                     |
   |                                     creates a temporary which is freed while still in use
...
55 |             let key = splitted_line.clone().nth(0).expect("incorrect line format");
   |                       --------------------- borrow later used here
   |
   = note: consider using a `let` binding to create a longer lived value

然而(由於某種原因我仍然不知道),當我運行下面的代碼時,它工作得很好:

let line = String::from("something=random");
let mut splitted_line = line.split("=");
let key = splitted_line.nth(0).expect("incorrect line format");
let value = splitted_line.nth(1).expect("incorrect line format");

據我從錯誤代碼描述中閱讀。 這不應該發生,因為我沒有從變量中借用任何值。

有人可以向我解釋為什么第一個代碼會引發臨時值錯誤,而為什么第二個不會?

split()正在借用。 它接受&self並返回一個迭代器,該迭代器產生&str引用self

代碼之間的區別在於何時釋放拆分的字符串:在第一個片段中,它是臨時的,因為我們立即對其調用一個方法,並在語句結束時釋放它( let mut splitted_line = String::from("something=random").split("="); )。 但是,由於我們使用了之后返回的字符串split() ,並且它們是從這個釋放的字符串中借用的,所以這是一個錯誤。

在第二種情況下,字符串不是臨時的,因為它綁定到一個變量,並且在 scope 的末尾被釋放。 因此,當我們使用split()返回的字符串時,它仍然存在。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM