如何在字符串、&str、Vec<u8> 之间进行转换和 &[u8]? [英] How do I convert between String, &str, Vec<u8> and &[u8]?

查看:34
本文介绍了如何在字符串、&str、Vec<u8> 之间进行转换和 &[u8]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

像我这样的新 Rustacean 很难处理这些类型:String&strVec&[u8].

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.

鉴于这些类型:

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]

推荐答案

来自 &str

  • &str ->String许多同样有效的方法:String::from(st)st.to_string(), st.to_owned().
    • 但我建议您在单个项目中坚持使用其中之一.String::from 的主要优点是您可以将其用作 map 方法的参数.因此,您通常可以使用 x.map(String::from) 代替 x.map(|s| String::from(s)).
    • From &str

      • &str -> String has many equally valid methods: String::from(st), st.to_string(), st.to_owned().
        • But I suggest you stick with one of them within a single project. The major advantage of String::from is that you can use it as an argument to a map method. So instead of x.map(|s| String::from(s)) you can often use x.map(String::from).
          • 字符串 ->&str 应该只是可以使用强制转换的 &s 或不可用的 s.as_str() .
          • 字符串 ->&[u8]&str -> 相同&[u8]: s.as_bytes()
          • 字符串 ->Vec 有一个自定义方法:s.into_bytes()
          • String -> &str should just be &s where coercion is available or s.as_str() where it is not.
          • String -> &[u8] is the same as &str -> &[u8]: s.as_bytes()
          • String -> Vec<u8> has a custom method: s.into_bytes()
          • &[u8] ->Vecu.to_owned()u.to_vec() 完成.它们做同样的事情,但 to_vec 有一点优势,就是它返回的类型没有歧义.
          • &[u8] ->&str 实际上并不存在,那就是 &[u8] ->结果<&str, Error>,通过str::from_utf8(u)提供
            • &[u8] -> Vec<u8> is done by u.to_owned() or u.to_vec(). They do the same thing, but to_vec has the slight advantage of being unambiguous about the type it returns.
            • &[u8] -> &str doesn't actually exist, that would be &[u8] -> Result<&str, Error>, provided via str::from_utf8(u)
              • str::from_utf8(u).unwrap() works, but you should prefer better error handling (see Error handling - The Result type).
              • String::from_utf8(u).unwrap() works, but prefer better error handling (see Error handling - The Result type and also Result::map.
              • Vec->&[u8] 应该只是 &v 可以使用强制,或者 as_slice 不可以.
              • Vec->&strVec 相同;->&[u8] ->结果<&str, Error>str::from_utf8(&v)
                • Vec<u8> -> &[u8] should be just &v where coercion is available, or as_slice where it's not.
                • Vec<u8> -> &str is the same as Vec<u8> -> &[u8] -> Result<&str, Error> i.e. str::from_utf8(&v)
                  • str::from_utf8(&v).unwrap() works, but prefer better error handling (see Error handling - The Result type)
                  • String::from_utf8(v).unwrap() works, but prefer better error handling (see Error handling - The Result type).

                  当目标不是通用的,而是分别明确输入为 &str&[u8] 时,就可以使用强制转换.Rustonomicon 有一章关于强制,其中包含有关强制网站的更多详细信息.

                  Coercion is available whenever the target is not generic but explicitly typed as &str or &[u8], respectively. The Rustonomicon has a chapter on coercions with more details about coercion sites.

                  &str    -> String  | String::from(s) or s.to_string() or s.to_owned()
                  &str    -> &[u8]   | s.as_bytes()
                  &str    -> Vec<u8> | s.as_bytes().to_vec() or s.as_bytes().to_owned()
                  String  -> &str    | &s if possible* else s.as_str()
                  String  -> &[u8]   | s.as_bytes()
                  String  -> Vec<u8> | s.into_bytes()
                  &[u8]   -> &str    | s.to_vec() or s.to_owned()
                  &[u8]   -> String  | std::str::from_utf8(s).unwrap(), but don't**
                  &[u8]   -> Vec<u8> | String::from_utf8(s).unwrap(), but don't**
                  Vec<u8> -> &str    | &s if possible* else s.as_slice()
                  Vec<u8> -> String  | std::str::from_utf8(&s).unwrap(), but don't**
                  Vec<u8> -> &[u8]   | String::from_utf8(s).unwrap(), but don't**
                  
                  * target should have explicit type (i.e., checker can't infer that)
                  
                  ** handle the error properly instead
                  

                  这篇关于如何在字符串、&amp;str、Vec&lt;u8&gt; 之间进行转换和 &amp;[u8]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆