Although i’m sure someone else has probably asked this question, i cannot seem to
grasp how to “think” about generics when dealing with functions that return types that may contain generics.
struct LinkedList<T> {
next: T
}
fn new<T>() -> LinkedList<T> {
LinkedList {
next: 42
}
}
fn main() {
let mut ls = new();
let mut lx = LinkedList { next: 12312 };
}
As i understood generics, if i assign a value to the next
field that should hold a T value(inside fn new
when assigning 42 to the next
field), it should work because T means/can hold any type(disregard traits). After discussing with some devs, they told me that the compiler cannot infer the type T declared in the impl(impl<T> LinkedList<T>....
).
If that is the case, why does this work let x = LinkedList { next: 12312 }
and why doesn’t the compiler throw a mismatch error? Why is the compiler complaining about 42 when i said that T is generic and can hold any value?
ps - I’m positive i haven’t really grasp generics and i kinda feel stupid about it
Thanks in advance,
Dragos