'@' 符号在 Rust 中有什么作用? [英] What does the '@' symbol do in Rust?

查看:50
本文介绍了'@' 符号在 Rust 中有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我忘记指定参数的类型,错误信息如下:

I forgot to specify the type of a parameter and the error message was as follows:

error: expected one of `:` or `@`, found `)`
 --> src/main.rs:2:12
  |
2 | fn func(arg)
  |            ^ expected one of `:` or `@` here

这就提出了一个问题:你可以用 @ 符号做什么?我不记得读过关于使用 @ 符号的内容.我也做了一些谷歌搜索,找不到任何东西.@ 有什么作用?

Which raises the question: what can you do with an @ symbol? I don't remember reading about using the @ symbol for anything. I also did some Googling and couldn't find anything. What does @ do?

推荐答案

您可以使用 @ 符号将模式绑定到名称.正如 Rust 参考文档 所示:

You can use the @ symbol to bind a pattern to a name. As the Rust Reference demonstrates:

let x = 1;

match x {
    e @ 1 ... 5 => println!("got a range element {}", e),
    _ => println!("anything"),
}

Rust 中的赋值 允许模式表达式(前提是它们是完整的)和参数列表也不例外.在 @ 的特定情况下,这不是很有用,因为您已经可以命名匹配的参数.但是,为了完整起见,这里有一个编译示例:

Assignments in Rust allow pattern expressions (provided they are complete) and argument lists are no exception. In the specific case of @, this isn't very useful because you can already name the matched parameter. However, for completeness, here is an example which compiles:

enum MyEnum {
    TheOnlyCase(u8),
}

fn my_fn(x @ MyEnum::TheOnlyCase(_): MyEnum) {}

这篇关于'@' 符号在 Rust 中有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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