Returning a template struct

Sorry for the series of stupid questions but I still have my training wheals on… The case is the following:

#[derive(Debug)]
pub struct AS<T> {
    x: T,
}

fn ret(i: i32) -> AS<_> {
    if i == 32i32 {
        let h: AS<_> = AS { x: 7i32 };
        return h;
    } else if i == 64i32 {
        let h: AS<_> = AS { x: 7i64 };
        return h;
    }
}

fn main() {
    let c = ret(32i32);
    println!("{:#?}", c);
}

So if i want to specify inside a function how my struct should look like and then return it. is this possible ? i know i could have specified it initially when defining c but is it possible to do it this way ? and if not why not ?

thank you

No, because the return type of a function must be uniform throughout all code branches. In the first branch you say return AS { x: 7i32 }; which makes the computer think your function returns AS<i32>, while the second one is return AS { x: 7i64 }, which would be AS<i64>. Rust had a solution though, it’s great enums which can help here. You could use an either-style enum or just use the crate for it.

2 Likes

The crate @OptimisticPeach is talking about is either

1 Like

Reading your code, I think you are trying to implement a function that returns an i32 when the caller wants an i32, and an i64 when the caller wants an i64. If that’s the case, why not have two function - ret_i32 and ret_i64?

Or, depending on your situation, maybe it would also make sense to impl From<YourStuff> for i32 and From<YourStuff> for i64

2 Likes

In Rust, without enum, types can’t depend on values. The closest you can do is to use a type parameter:

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=b186fa0258e09fcda86332392261755f

1 Like