Input type and return type in generic function

is it important that the input type as parameter and and return type type in generic function should be same?
is it possible to have a generic function with different input type as parameter and return type ?

Yes, it is possible. It sounds like you have a compile error, if you post the error and the related code we can help you fix it.

can give a simple example

fn collect_iterator<I, C>(iter: I) -> C
where
    I: IntoIterator,
    C: std::iter::FromIterator
{
    iter.into_iter().collect()
}

This can take anything that can be converted into an iterator and converts it into anything that can be built from an iterator.

Or a simpler example is

fn convert<A: Into<B>, B>(a: A) -> B {
    a.into()
}
1 Like

return type may various as usize,isize,char ...

I'm not sure what you are trying to ask, do you have a specific question or problem you are trying to solve?

1 Like

You can't have functions just generic over numeric types. Generics are based on traits, which are tied to specific methods you run.

See:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.