gpt4 book ai didi

rust - 是什么使 `impl Trait` 作为参数 "universal"和作为返回值 "existential"?

转载 作者:行者123 更新时间:2023-11-29 07:56:52 24 4
gpt4 key购买 nike

我正在阅读 RFC on "expanding" impl Trait当我遇到以下情况时:

By contrast, a programmer who first learned: fn take_iter(t: impl
Iterator)
and then tried: fn give_iter() -> impl Iterator would be successful, without any rigorous understanding that they just transitioned from a universal to an existential.

虽然我从逻辑角度理解普遍性与存在性,但为什么第一个高于普遍性而第二个高于存在性?

最佳答案

RFC 以多种方式多次定义术语:

between existential types (where the callee chooses the type) and universal types (where the caller chooses)

There's been a lot of discussion around universals vs. existentials (in today's Rust, generics vs impl Trait).

  • Universal quantification, i.e. "for any type T", i.e. "caller chooses". This is how generics work today. When you write fn foo<T>(t: T), you're saying that the function will work for any choice of T, and leaving it to your caller to choose the T.

  • Existential quantification, i.e. "for some type T", i.e. "callee chooses". This is how impl Trait works today (which is in return position only). When you write fn foo() -> impl Iterator, you're saying that the function will produce some type T that implements Iterator, but the caller is not allowed to assume anything else about that type.

长话短说:

  • fn take_iter(t: impl Iterator) — 调用 take_iter 的人选择具体类型。该函数必须适用于实现该特征的整个“宇宙”类型。

  • fn give_iter() -> impl Iteratorgive_iter 的实现选择具体类型。有一些类型“存在”并实现了函数将返回的特征。

关于rust - 是什么使 `impl Trait` 作为参数 "universal"和作为返回值 "existential"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47929824/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com