difficulties/string #1187
Replies: 16 comments 3 replies
-
let mut s = String::from("hello");
s.push_str(", world!"); // append a slice
println!("{}", s); // This will print: hello, world!
let s: &str = "Hello, world!";
println!("{}", s); // This will print: Hello, world!
let s = String::from("Hello, world!");
let t: &String = &s;
println!("{}", t); // This will print: Hello, world!
let s: Box<str> = Box::from("Hello, world!");
println!("{}", s); // This will print: Hello, world!
let s: &str = "Hello, world!";
let t: Box<&str> = Box::new(s);
println!("{}", t); // This will print: Hello, world! |
Beta Was this translation helpful? Give feedback.
-
例如 Unix 和 Windows。 在 Unix 中,字符串是以 \0 结尾的字节序列 (UTF-8),
|
Beta Was this translation helpful? Give feedback.
-
啥玩意儿! |
Beta Was this translation helpful? Give feedback.
-
直接看文档:The str type, also called a ‘string slice’, is the most primitive string type. It is usually seen in its borrowed form, &str. It is also the type of string literals, &'static str. |
Beta Was this translation helpful? Give feedback.
-
我写一下关于&str和String的转换以及其作为函数参数的相关心得。 值得注意的是,Rust的String没有copy on write机制(当然modern cpp也没有),因此不应当存在两个String共用一个字符串值区域。而&str是对String内部值区域的引用,可想而知,我们无法在&str所指的值区域上原地构建String。 &str转String的函数,我翻了翻,似乎本质上都是调用 与此同时,&str的功能简直残废(因为它要定义在no_std下,因此很多功能都没能装配),写它也会涉及无数生命周期问题。 为什么要强调这个?因为我们常常听说过函数参数为字符串的时候要用&str,因为它能适配&str、String和&String。但是,如果你的函数里面是要这字符串的所有权(或者说需要的其实是String)的话,就会产生多余的拷贝。 因此我有如下实践经验:
如果第二种情况下,外部参数依然需要String的所有权怎么办?那就让外部在传参的时候显式地Clone,也正好提醒程序员,这个函数里面有Clone,别传太大的字符串。 |
Beta Was this translation helpful? Give feedback.
-
difficulties/string
https://course.rs/difficulties/string.html
Beta Was this translation helpful? Give feedback.
All reactions