┌─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┐│ H │ e │ l │ l │ o │ │ W │ o │ r │ l │ d │└─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┘┌─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┐│ 72 │ 101 │ 108 │ 108 │ 111 │ 32 │ 87 │ 111 │ 114 │ 108 │ 100 │└─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┘
let ptr = s.as_mut_ptr();let len = s.len();let capacity = s.capacity();
let s = String::from_raw_parts(ptr, len, capacity);
从一个角色
let ch = 'c';let s = ch.to_string();
从字节向量
let hello_world = vec![72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100];// We know it is valid sequence, so we can use unwraplet hello_world = String::from_utf8(hello_world).unwrap();println!("{}", hello_world); // Hello World
// String is at heap, and can be increase or decrease in its size// The size of &str is fixed.fn main(){let a = "Foo";let b = "Bar";let c = a + b; //error// let c = a.to_string + b;}
use std::mem;
fn main() {// on 64 bit architecture:println!("{}", mem::size_of::<&str>()); // 16println!("{}", mem::size_of::<String>()); // 24
let string1: &'static str = "abc";// string will point to `static memory which lives through the whole program
let ptr = string1.as_ptr();let len = string1.len();
println!("{}, {}", unsafe { *ptr as char }, len); // a, 3// len is 3 characters long so 3// pointer to the first character points to letter a
{let mut string2: String = "def".to_string();
let ptr = string2.as_ptr();let len = string2.len();let capacity = string2.capacity();println!("{}, {}, {}", unsafe { *ptr as char }, len, capacity); // d, 3, 3// pointer to the first character points to letter d// len is 3 characters long so 3// string has now 3 bytes of space on the heap
string2.push_str("ghijk"); // we can mutate String type, capacity and length will aslo changeprintln!("{}, {}", string2, string2.capacity()); // defghijk, 8
} // memory of string2 on the heap will be freed here because owner goes out of scope
}