技术控

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

[其他] Optional arguments in Rust 1.12

[复制链接]
心情简历 投递于 2016-9-30 14:03:14
90 0
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
下一篇:[原]微服务设计的几点思考
我要投稿

推荐阅读


回页顶回复上一篇下一篇回列表
手机版/CoLaBug.com ( 粤ICP备05003221号 | 文网文[2010]257号 | 粤公网安备 44010402000842号 )

© 2001-2017 Comsenz Inc.

返回顶部 返回列表