gpt4 book ai didi

swift - "__consuming"在 Swift 中有什么作用?

转载 作者:IT王子 更新时间:2023-10-29 05:19:02 24 4
gpt4 key购买 nike

Sequence.swift 中有以__consuming 为前缀的函数(很可能还有其他地方,但我还没有真正环顾四周)。我知道它是某种类型的声明修饰符,但我不确定它的作用。

最佳答案

据我了解,__consuming 实际上还没有做任何事情。添加它是为了执行 move-only types。 ,此时它将用于表示一个方法,该方法消耗它被调用的值(即该值将从调用者移动到被调用者)。

为了说明,考虑这个伪代码:

// Foo is a move-only type, it cannot be copied.
moveonly struct Foo {
consuming func bar() { // Method is marked consuming, therefore `self` is moved into it.
print(self) // We now 'own' `self`, and it will be deinitialised at the end of the call.
}
}

let f = Foo()
f.bar() // `bar` is a `consuming` method, so `f` is moved from the caller to the callee.
print(f) // Invalid, because we no longer own `f`.

该属性目前以两个下划线为前缀,以表明在实际实现仅移动类型之前,用户不应使用它,届时它可能会重命名为 consuming .

正如您所发现的,一些标准库协议(protocol)要求 have been marked __consuming为了表明它们可以通过仅移动类型的消耗方法以及非消耗方法来满足。这与 mutating 协议(protocol)要求表明它可以通过值类型上的 mutating 方法或其他非突变方法来满足的方式非常相似(但据我所知,还没有实际的编译器逻辑支持对 __consuming 的检查。

例如,filter(_:)Sequence 的要求已标记为消耗,因为采用的仅移动元素序列需要能够移动将适用的元素放入结果数组中,从而使序列无效。

在 move-only 类型实现之前就添加该属性的原因是为 Swift 5 ABI 稳定性卡住做准备。 As Martin says , 这在论坛上有更详细的讨论:

关于swift - "__consuming"在 Swift 中有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51292799/

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