是什么使"impl特性"作为参数“通用"?并且作为返回值"existential"? [英] What makes `impl Trait` as an argument "universal" and as a return value "existential"?

查看:103
本文介绍了是什么使"impl特性"作为参数“通用"?并且作为返回值"existential"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 RFC当我遇到以下情况时,就可以扩展"隐式特质:

相比之下,一个程序员首先学会了:fn take_iter(t: impl Iterator),然后又尝试了:fn give_iter() -> impl Iterator 成功,没有任何严格的了解,他们只是 从普遍转变为存在.

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.

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

While I understand universal vs existential from a logic perspective, what makes the first one above universal and the second one existential?

推荐答案

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

The RFC defines the terms multiple times in multiple manners:

存在类型(被呼叫者选择类型)和通用类型(呼叫者选择类型)之间

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

关于通用性与存在性(在当今的Rust中,通用性与impl特性)进行了很多讨论.

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

  • 通用量化,即对于任何类型T",即调用者" 选择".这就是今天的泛型工作方式.当您编写时 fn foo<T>(t: T),您说的是该功能适用​​于任何 选择T,然后将其留给呼叫者以选择T.

  • 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.

现有量化,即对于某些类型T",即被呼叫者" 选择".这就是今天impl Trait的工作方式(作为回报 仅位置).当您写fn foo() -> impl Iterator时,您就是 说函数将产生某种实现的T类型 Iterator,但是不允许调用者承担其他任何事情 关于该类型.

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.

TL; DR:

  • fn take_iter(t: impl Iterator)-呼叫take_iter的人选择具体类型.该功能必须对实现特征的类型的整个宇宙"起作用.

  • fn take_iter(t: impl Iterator) — the person calling take_iter picks the concrete type. The function has to work for the entire "universe" of types that implement the trait.

fn give_iter() -> impl Iterator-give_iter的实现选择具体类型.有一些类型存在"并实现该函数将返回的特征.

fn give_iter() -> impl Iterator — the implementation of give_iter picks the concrete type. There is some type which "exists" and implements the trait that will be returned by the function.

这篇关于是什么使"impl特性"作为参数“通用"?并且作为返回值"existential"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆