首页 > 解决方案 > 为什么我不能声明具有元组参数匹配的特征函数?

问题描述

为什么我不能声明具有元组参数匹配的特征函数?

#![allow(unused)]

// This works
fn foo((x, y): (i32, i32)) {
}

trait Bar {
    // This does not work
    fn bar((x, y): (i32, i32));
}

操场

编译上述输出:

error: expected one of `)` or `,`, found `:`
 --> src/main.rs:7:18
  |
7 |     fn bar((x, y): (i32, i32));
  |                  ^ expected one of `)` or `,` here

error: expected one of `!`, `&&`, `&`, `(`, `)`, `*`, `<`, `?`, `[`, `_`, `dyn`, `extern`, `fn`, `for`, `impl`, `unsafe`, or lifetime, found `:`
 --> src/main.rs:7:18
  |
7 |     fn bar((x, y): (i32, i32));
  |                  ^ expected one of 17 possible tokens here

error[E0601]: `main` function not found in crate `playground`
  |
  = note: consider adding a `main` function to `src/main.rs`

标签: syntaxrusttraits

解决方案


Rust 不支持这种语法,目前还没有开放的 RFC 可以改变它。

在一个特征中,除了可能用于文档之外,它没有其他用途。但是,由于无论如何您都在定义特征,因此您可以首先为该参数定义一个更具描述性的类型。在您的情况下,Point带有xy字段。


推荐阅读