A new Rustacean like me struggles with juggling these types: String
, &str
, Vec<u8>
, &[u8]
.
In time, I hope to have an epiphany and suddenly get why some library calls use one or the other. Until then, I need help to map out each idiomatic transition.
Given these types:
let st: &str = ...;
let s: String = ...;
let u: &[u8] = ...;
let v: Vec<u8> = ...;
I think I have figured these out, but are they idiomatic?
&str -> String String::from(st)
&str -> &[u8] st.as_bytes()
String -> &str s.as_str()
&[u8] -> &str str::from_utf8(u)
Vec<u8> -> String String::from_utf8(v)
Ultimately I want a complete table of transitions for these types:
&str -> String
&str -> &[u8]
&str -> Vec<u8>
String -> &str
String -> &[u8]
String -> Vec<u8>
&[u8] -> &str
&[u8] -> String
&[u8] -> Vec<u8>
Vec<u8> -> &str
Vec<u8> -> String
Vec<u8> -> &[u8]
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…