7.2. Subtyping

Subtyping

Subtyping is implicit and can occur at any stage in type checking or inference. Subtyping in Rust is very restricted and occurs only due to variance with respect to lifetimes and between types with higher ranked lifetimes. If we were to erase lifetimes from types, then the only subtyping would be due to type equality.

Consider the following example: string literals always have 'static lifetime. Nevertheless, we can assign s to t:

# #![allow(unused_variables)]
#fn main() {
fn bar<'a>() {
    let s: &'static str = "hi";
    let t: &'a str = s;
}

#}

Since 'static "lives longer" than 'a, &'static str is a subtype of &'a str.

© 2010 The Rust Project Developers
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.
https://doc.rust-lang.org/reference/subtyping.html

在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号

意见反馈
返回顶部