Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

rust 生命周期泛型 #100

Open
Triment opened this issue Mar 12, 2024 · 0 comments
Open

rust 生命周期泛型 #100

Triment opened this issue Mar 12, 2024 · 0 comments
Labels
release 发布文章

Comments

@Triment
Copy link
Owner

Triment commented Mar 12, 2024

rust有一个生命周期泛型,这个可能在别的编程语言中是不存在的,这是由于rust要推断引用是否合法而增加的一项额外tips

具体的如下

fn extra_tips(a: &bool, b: &bool) -> &bool {
    if *a {
        b
    } else {
        a
    }
}

由于函数extra_tips返回的是参数的引用,但是编译器不知道a和b在具体的运行过程中实际返回哪一个,所以编译器不知到如何追踪返回的引用,追踪是防止 悬垂指针

再论rust生命周期的泛型形式

struct Item<'a,'b, T, U> {
    a: &'a T,
    b: &'b T,
    c: &'a U
}

'a表示生命周期泛型,类似于T,都是对具体变量的抽象,T是将实际传入的数据类型进行抽象(类型约束),'a则是对实际传入的数据生命周期进行抽象(生命周期约束),上面的例子中a和b有同样的数据类型, a和c有相同的生命周期(a活着,c就活着

@Triment Triment added the release 发布文章 label Mar 26, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
release 发布文章
Projects
None yet
Development

No branches or pull requests

1 participant