Constrain `usize: Add<N>`

How can I constrain a type parameter N in Rust such that it satisfies the requirement that usize implements the Add trait for N (i.e. impl<N> std::ops::Add<N> for usize)?


fn foo<N /* usize: Add<N> */>(num: N) {
    let _ = 2usize + num;

The syntax you need is a so-called “where clause”

fn foo<N>(num: N) where usize: Add<N> {

Rust Playground

For more information, see here, here, or here.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.