Into And AsRef Accept String Like Values
Take string parameters with impl Into<String> when ownership is needed and impl AsRef<str> for read-only borrows, so callers pass &str or String freely.
Code
// Into<String>:调用方决定是否转移所有权;AsRef<str>:只读借用,零拷贝
fn register_user(name: impl Into<String>) -> String {
// Into 消费参数:String 传入零开销,&str 传入才分配
let owned: String = name.into();
format!("registered: {owned}")
}
fn normalized_len(text: impl AsRef<str>) -> usize {
// AsRef 只借用:任何能借成 &str 的值都能传入
text.as_ref().trim().len()
}
fn main() {
// &str 传入 Into:需要时才分配出 String
println!("{}", register_user("alice"));
let heap_name = String::from("bob");
// String 传入 Into:所有权直接转移,没有第二次分配
println!("{}", register_user(heap_name));
// AsRef<str> 同时接受 &str 与 &String
println!("len static: {}", normalized_len(" carol "));
let owned = String::from(" dave ");
println!("len owned: {}", normalized_len(&owned));
// 被借用的值不受影响,之后仍可继续使用
println!("still usable: {}", owned.to_uppercase());
}What the code does
Into And AsRef Accept String Like Values keeps everything in the functions register_user, normalized_len and main.
Using it
The main signature reads fn register_user(name: impl Into<String>) -> String
The demo output is labeled (len static:, len owned:, still usable:), so every printed line maps back to its originating operation.
The demo flow inside main is register_user and normalized_len — run the file to see it end to end.
Key statements
fn register_user(name: impl Into<String>) -> String {
// Into 消费参数:String 传入零开销,&str 传入才分配
let owned: String = name.into();
format!("registered: {owned}")
}
fn normalized_len(text: impl AsRef<str>) -> usize {
// AsRef 只借用:任何能借成 &str 的值都能传入
text.as_ref().trim().len()
}
Interactive Tools for This Topic
Accept Header ParserParse an Accept header into media ranges with their quality values and specificity, sorted by preference for content negotiation debugging.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Into And AsRef Accept String Like Values print when run?
- The script runs standalone; its 3 labeled outputs include `len static:`, `len owned:`, `still usable:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.