Trait bound for integer type

⚓ Rust    📅 2025-04-28    👤 surdeus    👁️ 4      

surdeus

Warning

This post was published 115 days ago. The information described in this article may have changed.
struct Outer<T>
{
    a: T,
}

fn zero<T>() -> Outer<T>
{
    Outer { a: 0 }
}

10 | fn zero<T>() -> Outer<T>
   |         - expected this type parameter
...
14 |     Outer { a: 0 }
   |                ^ expected type parameter `T`, found integer
   |
   = note: expected type parameter `T`
                        found type `{integer}`

OK, so I understand why this doesn't work: I've not told the compiler that T is always going to be a numeric type. But how do I tell the compiler this? I have googled around and people have suggested "use num::Integer but the docs aren't super clear for my use case. I tried this:

use num::Integer;

struct Outer<T>
where
    T: Integer,
{
    a: T,
}

fn zero<T>() -> Outer<T>
where
    T: Integer,
{
    Outer { a: 0 }
}

But I get basically the same error. What am I missing here?

Playground link

3 posts - 3 participants

Read full topic

🏷️ rust_feed