[英]How to convert a String into a &'static str
如何將String
轉換為&str
? 更具體地講,我想將它轉換成一個str
與static
壽命( &'static str
)。
為 Rust 1.0 更新
您無法從String
獲取&'static str
因為String
s 可能不會在您的程序的整個生命周期中都存在,而這就是&'static
生命周期的含義。 您只能從中獲取由String
自己的生命周期參數化的切片。
要從String
到 slice &'a str
您可以使用切片語法:
let s: String = "abcdefg".to_owned();
let s_slice: &str = &s[..]; // take a full slice of the string
或者,您可以使用String
實現Deref<Target=str>
並執行顯式重新借用的事實:
let s_slice: &str = &*s; // s : String
// *s : str (via Deref<Target=str>)
// &*s: &str
還有另一種允許更簡潔語法的方法,但它只能在編譯器能夠確定所需的目標類型(例如在函數參數或顯式類型化的變量綁定中)時使用。 它被稱為deref coercion ,它允許只使用&
運算符,編譯器將根據上下文自動插入適量的*
s:
let s_slice: &str = &s; // okay
fn take_name(name: &str) { ... }
take_name(&s); // okay as well
let not_correct = &s; // this will give &String, not &str,
// because the compiler does not know
// that you want a &str
請注意,此模式對於String
/ &str
不是唯一的 - 您可以將它用於通過Deref
連接的每一對類型,例如,來自std::ffi
模塊的CString
/ CStr
和OsString
/ OsStr
或來自std::path
PathBuf
/ Path
std::path
模塊。
您可以這樣做,但它涉及泄漏String
的內存。 這不是你應該輕易做的事情。 通過泄漏String
的內存,我們保證內存永遠不會被釋放(因此泄漏)。 因此,對內部對象的任何引用都可以解釋為具有'static
生命周期”。
fn string_to_static_str(s: String) -> &'static str {
Box::leak(s.into_boxed_str())
}
fn main() {
let mut s = String::new();
std::io::stdin().read_line(&mut s).unwrap();
let s: &'static str = string_to_static_str(s);
}
從 Rust 1.26 版開始,可以在不使用unsafe
代碼的情況下將String
轉換為&'static str
:
fn string_to_static_str(s: String) -> &'static str {
Box::leak(s.into_boxed_str())
}
這會將String
實例轉換為裝箱的str
並立即泄漏它。 這釋放了字符串當前可能占用的所有多余容量。
請注意,幾乎總是有比泄漏對象更可取的解決方案,例如,如果您想在線程之間共享狀態,請使用crossbeam
crate。
TL;DR:您可以從本身具有'static
生命周期'static
的String
獲取&'static str
。
盡管其他答案是正確且最有用的,但有一個(不太有用的)邊緣情況,您確實可以將String
轉換為&'static str
:
引用的生命周期必須始終短於或等於被引用對象的生命周期。 即被引用的對象必須比引用的壽命更長(或等於)。 由於'static
意味着程序的整個生命周期,因此不存在更長的生命周期。 但平等的一生就足夠了。 因此,如果String
的生命周期為'static
,則可以從中獲取&'static str
引用。
當const fn
功能發布時,Rust 1.31 理論上可以創建String
類型的static
。 不幸的是,目前唯一返回String
const 函數是String::new()
,它仍然在功能門之后(所以現在需要 Rust nightly )。
所以下面的代碼進行了所需的轉換(每晚使用)......實際上沒有實際用途,除了完整地表明在這種邊緣情況下是可能的。
#![feature(const_string_new)]
static MY_STRING: String = String::new();
fn do_something(_: &'static str) {
// ...
}
fn main() {
do_something(&MY_STRING);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.