Skip to Content
Rust Programming By Example
book

Rust Programming By Example

by Guillaume Gomez, Antoni Boucher
January 2018
Beginner to intermediate
454 pages
10h 8m
English
Packt Publishing
Content preview from Rust Programming By Example

 Explaining the Some function

Generally, when a function expects an Option argument, it looks like this:

fn some_func(arg: Option<&str>) {
    // some code
}

And you call it as follows:

some_func(Some("ratatouille"));
some_func(None);

Now, what if I told you that you could get rid of the Some? Nice, right? Well, this is actually pretty easy:

fn some_func<'a, T: Into<Option<&'a str>>>(arg: T) {
    // some code
}

And you can now call it as follows:

some_func(Some("ratatouille")); // If you *really* like to write "Some"...
some_func("ratatouille");
some_func(None);

Better! However, to make users' lives easier, it'll require a bit more code for whoever's writing the function. You can't use arg as it is; you need to add an extra step. Before, you'd just ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Rust Programming Cookbook

Rust Programming Cookbook

Claus Matzinger
Rust Web Programming

Rust Web Programming

Maxwell Flitton

Publisher Resources

ISBN: 9781788390637Supplemental Content