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 重写 SQLite 数据库(二):是否有市场空间?
数据库·rust·sqlite
烈风15 小时前
004 Rust控制台打印输出
开发语言·后端·rust
a73601516 小时前
二十二、包管理与发布 (Cargo 进阶)
开发语言·rust
编码浪子19 小时前
趣味学RUST基础篇(异步补充)
开发语言·后端·rust
烈风19 小时前
003 cargo使用
rust·cargo
songroom19 小时前
Rust : 关于Deref
开发语言·后端·rust
穷人小水滴1 天前
胖喵必快 (pmbs): btrfs 自动快照工具 (每分钟快照)
linux·rust
钢门狂鸭1 天前
关于rust的crates.io
开发语言·后端·rust
编码浪子1 天前
趣味学RUST基础篇(异步)
服务器·rust·负载均衡
勇敢牛牛_2 天前
使用Rust实现服务配置/注册中心
开发语言·后端·rust·注册中心·配置中心