It is related to my original question regarding parameterization with impl Trait.
How to write a function returning a value of type defined outside of the function?
Is it possible to adapt the code to reach the goal without using impl Trait and keeping control of returned type outside of the function?
use core::fmt::Display;
fn main() {
let x = problem::<i32>();
println!("{}", x);
let x = problem::<i64>();
println!("{}", x);
}
//
pub fn problem<ContainerEnd>() -> ContainerEnd
where
ContainerEnd: Display,
{
let on_end = 13;
on_end
}
I think it has already been discussed, but -> impl Trait is for "the function chooses what type to return" and a parameterized type is for "the caller chooses which type to get back".
Both have their uses but do different things, and both are in common use.
So we could explain how the parameterization works but it sounds like it's not useful for what you wanted to do with the question in the other topic.
Good, so for your problem function to compile, the body of the function can only use features allowed by the trait bounds on that generic parameter. Unfortunately, assigning the value 13 is not allowed by any there. But if you had a trait bound like From<i32>, it could be, then you could call ThatType::from(13). That's just an example.
But if you had a trait bound like From<i32> , it could be, then you could call ThatType::from(13) . That's just an example.
I have reached the goal with Default trait. Is it possible to reach the goal with Into/From?
fn main() {
let x = problem::<i32>();
println!("{}", x);
let x = problem::<i64>();
println!("{}", x);
}
pub fn problem<T>() -> T
where
T: Default,
{
T::default()
}
use ::core::fmt::Display;
fn main ()
{
let x = problem::<i32>();
println!("{}", x);
let x = problem::<i64>();
println!("{}", x);
}
//
pub fn problem<ContainerEnd>() -> ContainerEnd
where
ContainerEnd : Display, // Not necessary, but ok
// ContainerEnd : From<u8>, /* slightly better than this: */
u8 : Into<ContainerEnd>,
{
let on_end = 13_u8;
on_end.into()
}