Advertisement
NLinker

Conversion between String, str, Vec<u8>, Vec<char>

Aug 28th, 2021
1,764
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.59 KB | None | 0 0
  1. use std::str;
  2.  
  3. fn main() {
  4.   // -- FROM: vec of chars --
  5.   let src1: Vec<char> = vec!['j','{','"','i','m','m','y','"','}'];
  6.   // to String
  7.   let string1: String = src1.iter().collect::<String>();
  8.   // to str
  9.   let str1: &str = &src1.iter().collect::<String>();
  10.   // to vec of byte
  11.   let byte1: Vec<u8> = src1.iter().map(|c| *c as u8).collect::<Vec<_>>();
  12.   println!("Vec<char>:{:?} | String:{:?}, str:{:?}, Vec<u8>:{:?}", src1, string1, str1, byte1);
  13.  
  14.   // -- FROM: vec of bytes --
  15.   // in rust, this is a slice
  16.   // b - byte, r - raw string, br - byte of raw string
  17.   let src2: Vec<u8> = br#"e{"ddie"}"#.to_vec();
  18.   // to String
  19.   // from_utf8 consume the vector of bytes
  20.   let string2: String = String::from_utf8(src2.clone()).unwrap();
  21.   // to str
  22.   let str2: &str = str::from_utf8(&src2).unwrap();
  23.   // to vec of chars
  24.   let char2: Vec<char> = src2.iter().map(|b| *b as char).collect::<Vec<_>>();
  25.   println!("Vec<u8>:{:?} | String:{:?}, str:{:?}, Vec<char>:{:?}", src2, string2, str2, char2);
  26.  
  27.   // -- FROM: String --
  28.   let src3: String = String::from(r#"o{"livia"}"#);
  29.   let str3: &str = &src3;
  30.   let char3: Vec<char> = src3.chars().collect::<Vec<_>>();
  31.   let byte3: Vec<u8> = src3.as_bytes().to_vec();
  32.   println!("String:{:?} | str:{:?}, Vec<char>:{:?}, Vec<u8>:{:?}", src3, str3, char3, byte3);
  33.  
  34.   // -- FROM: str --
  35.   let src4: &str = r#"g{'race'}"#;
  36.   let string4 = String::from(src4);
  37.   let char4: Vec<char> = src4.chars().collect();
  38.   let byte4: Vec<u8> = src4.as_bytes().to_vec();
  39.   println!("str:{:?} | String:{:?}, Vec<char>:{:?}, Vec<u8>:{:?}", src4, string4, char4, byte4);
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement