WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Rust · Advanced · question 51 of 100

Explain the concept of variance in Rust, and how it relates to lifetimes and type parameters.?

📕 Buy this interview preparation book: 100 Rust questions & answers — PDF + EPUB for $5

In Rust, variance refers to how subtyping between two types is affected by lifetimes and type parameters. Specifically, it determines how "`Foo<X>‘ is a subtype of ‘Foo<Y>‘" when ‘X‘ is a subtype of ‘Y‘, and how lifetimes in subtypes relate to those in their supertypes.

Rust supports two kinds of variance: covariance and contravariance. Co means "together" or "same direction," and contra means "against." In covariance, the subtyping relationship between two types is preserved when their type parameters have the same direction. For example, a ‘Vec<i32>‘ is a subtype of ‘Vec<u32>‘ if ‘i32‘ is a subtype of ‘u32‘, because the ‘Vec<T>‘ type is covariant in its type parameter ‘T‘. This means that a ‘Vec<i32>‘ can be used in the same way as a ‘Vec<u32>‘ wherever a ‘Vec<T>‘ is expected. Lifetimes are also covariant, which means that a function that takes a reference with a longer lifetime can be used in place of a function that takes a reference with a shorter lifetime.

Contravariance, on the other hand, is when the subtyping relationship between two types is reversed when their type parameters have opposite directions. This is useful when a function or struct takes a generic argument but only uses it in a particular way, such as taking a reference to it. In this case, the function or struct can be contravariant in the type parameter to ensure that no unexpected behavior occurs. For example, the function ‘f(&’a T)‘ is contravariant in ‘’a‘ because if ‘T‘ is covariant, it might be possible to pass it a reference to a type ‘U‘ with a shorter lifespan than ‘’a‘, leading to undefined behavior.

Overall, variance is an important concept in Rust because it helps ensure that generic code is safe and behaves as expected. By enforcing the correct variance between lifetimes and type parameters, Rust can help prevent bugs and errors that might otherwise be difficult to catch.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Rust interview — then scores it.
📞 Practice Rust — free 15 min
📕 Buy this interview preparation book: 100 Rust questions & answers — PDF + EPUB for $5

All 100 Rust questions · All topics