rust中的惯用类型转换String,&str,&[u8],Vec

Conversion From To Method(s)
&str -> String &str String String::from(s), s.to_string(), s.to_owned()
&str -> &[u8] &str &[u8] s.as_bytes()
&str -> Vec &str Vec s.as_bytes().to_vec() or s.as_bytes().to_owned()
String -> &str String &str &s if possible* else s.as_str()
String -> &[u8] String &[u8] s.as_bytes()
String -> Vec String Vec s.into_bytes()
&[u8] -> &str &[u8] &str std::str::from_utf8(s).unwrap()
&[u8] -> String &[u8] String String::from_utf8(s).unwrap()
&[u8] -> Vec &[u8] Vec s.to_vec()
Vec -> &str Vec &str std::str::from_utf8(&s).unwrap()
Vec -> String Vec String String::from_utf8(s).unwrap()
Vec -> &[u8] Vec &[u8] &s if possible* else s.as_slice()

*注意:将 String 转换为 &str 或将 Vec 转换为 &str 或 &[u8] 可能会导致悬挂引用,应该确保 String 或 Vec 在生命周期内有效。

相关推荐
mit6.82413 小时前
rust等于C++的最佳实践
rust
初恋叫萱萱21 小时前
基于 Rust 与 DeepSeek 构建高性能 Text-to-SQL 数据库代理服务
数据库·sql·rust
鸿乃江边鸟1 天前
Spark Datafusion Comet 向量化Rust Native--执行Datafusion计划
大数据·rust·spark·native
鸿乃江边鸟2 天前
Spark Datafusion Comet 向量化Rust Native--创建Datafusion计划
rust·spark·native
咸甜适中2 天前
rust的docx-rs库,自定义docx模版批量分页生成一个docx文档(方便打印)(逐行注释)
rust·办公自动化·docx-rs
Vallelonga2 天前
Rust Option.as_ref() 方法
开发语言·rust
大卫小东(Sheldon)3 天前
GIM 2.0 发布:真正让 AI 提交消息可定制、可控、可项目级优化
git·rust·gim
roamingcode3 天前
我是如何 Vibe Coding,将 AI CLI 工具从 Node.js 迁移到 Rust 并成功发布的
人工智能·rust·node.js·github·claude·github copilot
初恋叫萱萱3 天前
构建高性能生成式AI应用:基于Rust Axum与蓝耘DeepSeek-V3.2大模型服务的全栈开发实战
开发语言·人工智能·rust
superman超哥4 天前
Serde 性能优化的终极武器
开发语言·rust·编程语言·rust serde·serde性能优化·rust开发工具