bright-star
bright-star

Reputation: 6447

Is it possible to vary the return type annotation of a function based on its input value?

I'd like to have a function that takes in a length argument, and returns an array that has that length:

fn make_zeros(length: &i16) -> [f64; length] {
    return [0; length]
}

Is there a rustic way of doing this, or should I just use a Vec?

Upvotes: 1

Views: 67

Answers (2)

llogiq
llogiq

Reputation: 14521

You can of course use macros to provide versions of your function for statically known lengths. Look at the arrayref crate for some macros with a similar scheme.

Upvotes: 2

Chris Morgan
Chris Morgan

Reputation: 90762

Types cannot at present be generic over numbers, which that would require. It is generally expected that something along those lines will happen at some point, but there is no schedule for it.

Your example would end up something like this:

fn make_zeroes<N: usize>() -> [f64; N] {
    return [0; N]
}

Note that this would be requiring constants; it’s never going to be possible to do it with anything other constants—a type must be known at compile time.

Upvotes: 3

Related Questions