技术控

    今日:104| 主题:49431
收藏本版 (1)
最新软件应用技术尽在掌握

[其他] Optional arguments in Rust 1.12

[复制链接]
心情简历 发表于 2016-9-30 14:03:14
70 0

立即注册CoLaBug.com会员,免费获得投稿人的专业资料,享用更多功能,玩转个人品牌!

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
Today’s    announcement of Rust 1.12contains, among other things, this innocous little tidbit:  
      Optionimplements    Fromfor its contained type  
  If you’re not very familiar with it,    Fromis a basic    converstion traitwhich any Rust type can implement. By doing so, it defines how to create its values    fromsome other type — hence its name.  
  Perhaps the most widespread application of this trait (and its    frommethod) is allocating owned    Stringobjects from literal    strvalues:  
  1. let hello = String::from("Hello, world!");
复制代码
What the change above means is that we can do similar thing with the    Optiontype:  
  1. let maybe_int = Option::from(42);
复制代码
At a first glance, this doesn’t look like a big deal at all. For one, this syntax is much more wordy than the traditional    Some(42), so it’s not very clear what benefits it offers.  
  But this first impression is rather deceptive. In many cases, this change can actually    reducethe number of times we have to type    Some(x), allowing us to replace it with just    x. That’s because this new    implbrings Rust quite a bit closer to having    optional function argumentsas a first class feature in the language.  
  Until now, a function defined like this:
  1. fn maybe_plus_5(x: Option<i32>) -> i32 {
  2.     x.unwrap_or(0) + 5
  3. }
复制代码
was the closest Rust had to default argument values. While this works perfectly — and is bolstered by compile-time checks! — callers are unfortunately required to build the    Optionobjects manually:  
  1. let _ = maybe_plus_5(Some(42));  // OK
  2. let _ = maybe_plus_5(None);      // OK
  3. let _ = maybe_plus_5(42);        // error!
复制代码
After    Option<T>implements    From<T>, however, this can change for the better.    Muchbetter, in fact, for the last line above can be made valid. All that is necessary is to take advantage of this new    implin the function definition:  
  1. fn maybe_plus_5<T>(x: T) -> i32 where Option<i32>: From<T> {
  2.     Option::from(x).unwrap_or(0) + 5
  3. }
复制代码
Unfortunately, this results in quite a bit of complexity, up to and including the    whereclause: a telltale sign of convoluted, generic code. Still, this trade-off may be well worth it, as a function defined once can be called many times throughout the code base, and possibly across multiple crates if it’s a part of the public    API.  
  But we can do better than this. Indeed, using the    Fromtrait to constrain argument types is just complicating things for no good reason. What we should so instead is use the symmetrical trait,          Into    , and take advantage of its standard    impl:  
  1. impl<T, U> Into<U> for T where U: From<T>
复制代码
Once we translate it to the    Optioncase (now that    Option<T>implements    From<T>), we can switch the trait bounds around and get rid of the    whereclause completely:  
  1. fn maybe_plus_5<T: Into<Option<i32>>>(x: T) -> i32 {
  2.     x.into().unwrap_or(0) + 5
  3. }
复制代码
As a small bonus, the function body has also gotten a little simpler.
  So, should you go wild and change all your functions taking    Optionals to look like this?… Well, technically you can, although the benefits may not outweigh the downsides for small, private functions that are called infrequently.  
  On the other hand, if you can afford to only support Rust 1.12 and up, this technique can make it much more pleasant to use the external    APIof your crates.  
  What’s best is the    full backward compatibilitywith any callers that still pass    Some(x): for them, the old syntax will continue to work exactly like before. Also note that the Rust compiler is smart about eliding the no-op conversion calls like the    Into::intoabove, so you shouldn’t observe any changes in the performance department either.  
  And who knows, maybe at some point Rust makes the final leap, and allows skipping the    Nones?…
友荐云推荐




上一篇:Hallucinating Machines Generate Tiny Video Clips
下一篇:[原]微服务设计的几点思考
酷辣虫提示酷辣虫禁止发表任何与中华人民共和国法律有抵触的内容!所有内容由用户发布,并不代表酷辣虫的观点,酷辣虫无法对用户发布内容真实性提供任何的保证,请自行验证并承担风险与后果。如您有版权、违规等问题,请通过"联系我们"或"违规举报"告知我们处理。

*滑动验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

我要投稿

推荐阅读

扫码访问 @iTTTTT瑞翔 的微博
回页顶回复上一篇下一篇回列表手机版
手机版/CoLaBug.com ( 粤ICP备05003221号 | 文网文[2010]257号 )|网站地图 酷辣虫

© 2001-2016 Comsenz Inc. Design: Dean. DiscuzFans.

返回顶部 返回列表