元组点符号的原因 [英] Reasons for Dot Notation for Tuple
问题描述
是否有任何技术原因 Rust 被设计为对元组使用点表示法而不是使用索引表示法(t[2]
)?
let t = (20u32, true, 'b')t.2//->'乙'
点符号在访问结构和对象的属性时似乎很自然.我在网上找不到资源或解释.
这个决定是在 RFC 184.动机部分有详细信息:
<块引用>现在访问元组和元组结构的字段非常痛苦——必须单独依靠模式匹配来提取值.这变成了一个问题,以至于在标准库 (core::tuple::Tuple*)
中创建了 12 个特征,使元组值访问更容易,添加了 .valN()
、.refN()
和 .mutN()
方法来帮助解决这个问题.但这不是一个很好的解决方案——它需要在标准库中实现特征,而不是语言,并且在使用时导入这些特征.总的来说,这不是问题,因为大部分时间 std::prelude::*
是导入的,但这仍然是一个 hack,不是手头问题的真正解决方案.它还只支持长度最多为 12 的元组,这通常不是问题,但强调当前情况有多糟糕.
相关拉取请求中的讨论也很有用.>
Is there any technical reason Rust is designed to use dot notation for tuples instead of using index notation (t[2]
)?
let t = (20u32, true, 'b')
t.2 // -> 'b'
Dot notation seems natural in accessing struct's and object's properties. I couldn't find a resource or explanation online.
This decision was made in RFC 184. The Motivation section has details:
Right now accessing fields of tuples and tuple structs is incredibly painful—one must rely on pattern-matching alone to extract values. This became such a problem that twelve traits were created in the standard library
(core::tuple::Tuple*)
to make tuple value accesses easier, adding.valN()
,.refN()
, and.mutN()
methods to help this. But this is not a very nice solution—it requires the traits to be implemented in the standard library, not the language, and for those traits to be imported on use. On the whole this is not a problem, because most of the timestd::prelude::*
is imported, but this is still a hack which is not a real solution to the problem at hand. It also only supports tuples of length up to twelve, which is normally not a problem but emphasises how bad the current situation is.
The discussion in the associated pull request is also useful.
这篇关于元组点符号的原因的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!