"Option" and "where S: Into<String>"

Rust looks very interesting… I have something like this:
pub fn new<S: Into < String > >(first_name: S, last_name: S, age: u8, university: Option < String > ) -> Person

why is it not working if I change it to “university: Option< S >”?

It will convert String (not really) or &str on other parameters. Is it possible to change “where” in a way to do the same thing for Option? Thx!

Using an Option<S> is perfectly valid given only the info we’ve been given.
Technically you could say where Option<S>: Into<String> but that most likely isn’t what you want to do.
Please share some more code to elaborate the errors your code presents.

1 Like

What I would like to get is that I can send Option < &str > or Option < String > into a function parameter… (Option < Something > where < who knows > :wink: )

I can send &str or String to the same function parameter when I add "where S: Into < String > ".

What I would like to do is the same thing for Option<&str> and Option < String >.

I can define that parameter as Option < String > but then I have to convert from &str to String every time I call that function with a &str — Some(“something”.to_string());

For example this is not working:

fn test< S>(str: Option< S>) where
S: Into< String> {
println!(“test {}”, str.into());
}

fn main() {
test(Some(“something”));
test(Some(“something”.to_string()));
}

You have to “remove” the Option layer first using unwrap or match or if let,…
For example:

println!("test {}", str.unwrap().into());
2 Likes

omg… Thx! :smiley:

Instead of being generic over <S : Into<String>> and then using S in the signature, you can also use impl Into<String> wherever S was used, which will implicitly declare as many generic parameters as there are occurrences of S. This has the advantage of, in your example, allowing to have first_name: &str and last_name: String.

1 Like

Thank you, Yandros. Much appreciated.