String::from, String::push_str, Deref to str
String::from(s: &str) -> String
fn push_str(&mut self, string: &str)
fn as_str(&self) -> &str
fn len(&self) -> usizeBuild an owned String, append borrowed text, and re-borrow it as &str. len reports bytes, not Unicode scalar values.
| Parameter | Description |
|---|---|
s / string | A UTF-8 string slice to copy or append. push_str takes &str and does not take ownership of a String unless you pass &owned. |
Returns: from returns an owned String. as_str returns a borrowed &str tied to the lifetime of the String. len returns the byte count.
- "Go语言" is 8 bytes: two ASCII bytes for Go and three bytes for each of the following two characters.
- The inner block ends the borrow of text so that push('!') can run afterward. Keeping borrowed in the same scope would not compile.
fn main() {
let mut text = String::from("Go");
text.push_str("语言");
{
let borrowed: &str = &text;
println!("{borrowed} bytes={}", borrowed.len());
}
text.push('!');
println!("{text}");
}Expected output
Go语言 bytes=8
Go语言!Related: String