我正在尝试使用超级库来发出一些请求。 Headers::get()
方法返回var voipRegistry: PKPushRegistry!
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
voipRegistry = PKPushRegistry(queue: DispatchQueue.main)
voipRegistry.delegate = self
voipRegistry.desiredPushTypes = Set([.voIP])
}
extension AppDelegate: PKPushRegistryDelegate {
func pushRegistry(_ registry: PKPushRegistry, didInvalidatePushTokenForType type: PKPushType) {
print("didInvalidatePushTokenForType")
}
func pushRegistry(_ registry: PKPushRegistry, didReceiveIncomingPushWith payload: PKPushPayload, forType type: PKPushType) {
print("Incoming voip notfication: \(payload.dictionaryPayload)")
}
func pushRegistry(_ registry: PKPushRegistry, didUpdate credentials: PKPushCredentials, forType type: PKPushType) {
print("voip token: \(credentials.token)")
}
}
,其中Option<&H>
是一个带有一个字段的元组结构。我可以使用H
来解构if let Some()
。但是我们如何解构Option
?当然,我总是可以使用&H
访问该字段,但我很好奇Rust是否有语法来执行此操作。
.0
答案 0 :(得分:3)
当您尝试编译它时,Rust编译器将告诉您如何使用一条好消息修复错误:
error[E0507]: cannot move out of borrowed content
--> <anon>:11:9
|
11 | let &s(bar) = f(&my_struct2); // this does not work
| ^^^---^
| | |
| | hint: to prevent move, use `ref bar` or `ref mut bar`
| cannot move out of borrowed content
这需要告诉编译器你只需要引用struct中的字段;默认匹配将执行移动,原始struct值将不再有效。
让我们修复一下这个例子:
struct s(String);
fn f(input: &s) -> &s {
input
}
fn main() {
let my_struct1 = s("a".to_owned());
let s(foo) = my_struct1;
let my_struct2 = s("b".to_owned());
let &s(ref bar) = f(&my_struct2);
}
另一种方法是先解除引用并删除&
。我认为这在Rust中是首选:
struct s(String);
fn f(input: &s) -> &s {
input
}
fn main() {
let my_struct1 = s("a".to_owned());
let s(foo) = my_struct1;
let my_struct2 = s("b".to_owned());
let s(ref bar) = *f(&my_struct2);
}