Why rust function doesn't support default generic type?

Here is a simple demo.

fn test1<T = Vec<Vec<Vec<i32>>>>() -> Vec<T> {
  let arr = vec![];
  return arr;
# get error
84 | fn test1<T = Vec<Vec<Vec<i32>>>>() -> Vec<T> {
   |          - this type parameter        ------ expected `Vec<T>` because of return type
87 |   return arr;
   |          ^^^ expected type parameter `T`, found struct `Vec`
   = note: expected struct `Vec<T>`
              found struct `Vec<Vec<Vec<{integer}>>>`

If T isn’t Vec<Vec<i32>>, then return arr; won’t work because the type of arr, Vec<Vec<Vec<i32>>>, is not the same type as Vec<T>. Rust wants your function definition to work for all possible instances of T, so it rejects your definition because of that statement.

(To be more precise, arr could be a Vec<Vec<Vec<u64>>>, or a Vec<Vec<Vec<usize>>>, for instance, since integer literals don’t have a particular type that they’re forced to be.)

Thanks. Now I understand it.

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.