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 在生命周期内有效。

相关推荐
小杍随笔2 分钟前
【Rust 语言编程知识与应用:闭包详解】
开发语言·后端·rust
Ivanqhz1 小时前
图着色寄存器分配算法(Graph Coloring)
开发语言·javascript·python·算法·蓝桥杯·rust
42tr_k15 小时前
Rust LanceDB 内存不足问题
rust
Source.Liu20 小时前
【Iced】benches 文件夹分析笔记
rust·iced
Source.Liu1 天前
【glam】线性代数库 lib.rs 文件解析
rust·glam
大黄说说1 天前
Rust 入门到实战:构建安全、高性能的下一代系统
开发语言·安全·rust
好家伙VCC1 天前
# 发散创新:用 Rust构建高并发虚拟世界引擎核心模块在当今游戏开发与元宇宙构建中,**虚拟世界的性能瓶颈往往不是图形渲染,而是底
java·开发语言·python·rust·图形渲染
Mr -老鬼1 天前
前后端联调避坑!Vue优先IPv6导致接口不通,Rust Salvo这样解决
前端·vue.js·rust
Source.Liu1 天前
【glam】断言宏解析
rust·glam
咚为1 天前
告别 lazy_static:深度解析 Rust OnceCell 的前世今生与实战
开发语言·后端·rust