Tuples and optional parameters in functions

Tuples and opional values

I am creating a function that accepts a tuple as a param:

fn test(t:(String, String, String, String, i32, bool)){}

Can I tell the compiler to have an either type? Either String | Nothing

What I would like to do is something like

test(("1","2",null,"4",100,false))
or
test(("1","2", _,"4",100, _))

This is more like optional parameters.

Is it possible in rust?
What are good practices?

Also is there a way to avoid String::from("1") when filling a tuple with string values?
&str causing issues.

What you are looking for is Option:

https://doc.rust-lang.org/book/ch06-01-defining-an-enum.html?highlight=option#the-option-enum-and-its-advantages-over-null-values

As for String::from("1"), the only other ways I know of are "1".to_string() or format!("1")

there is also to_owned().
its weird that rust has all these options.

I am not a language designer, nor am I super familiar with Rust's design; but to me, these are all somewhat generic methods, and the fact that they all do the same thing for a &str to a String is more coincidence. Sometimes you will do the same thing even if the reason is different!

Usually choice is between builder or a derive macro.

That's for when you need to build something really complex. For simple cases Option may be sufficient or just a few functions with different names.

1 Like

There are more ways than listed, too -- a large reason for it is that many of the choices are trait methods, and the traits are designed around (sometimes subtly) different goals and promises -- but the &str to String conversion happens to satisfy a great many of them. For instance the ToOwned trait is tied to the Borrow trait, which has specific conditions for behaving reasonably (e.g. in a HashMap implementation); the relationship between str and String meets these conditions.

(Another reason is that working with text is common, and str and String are the main representation of text in Rust, so things like the format machinery or parsing machinery also happen to produce Strings / consume &strs.)

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.