Reasons for Dot Notation for Tuple

后端 未结 4 2012
挽巷
挽巷 2021-01-11 09:20

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\         


        
4条回答
  •  逝去的感伤
    2021-01-11 10:05

    I want to provide an answer from my experience using a functional language (Ocaml) for the while since I've posted this question.

    Apart from @rom1v reference, indexing syntax like a[0] everywhere else also used in some kind of sequence structure, of which tuples aren't. In Ocaml, for instance, a tuple (1, "one") is said to have type int * string, which conforms to the Cartesian product in mathematics (i.e., the plane is R^2 = R * R). Plus, accessing a tuple by nth index is considered unidiomatic.

    Due to its polymorphic nature, a tuple can almost be thought of as a record / object, which often prefer dot notation like a.fieldName as a convention to access its field (except in language like Javascript, which treats objects like dictionaries and allows string literal access like a["fieldname"]. The only language I'm aware of that's using indexing syntax to access a field is Lua.

    Personally, I think syntax like a.(0) tends to look better than a.0, but this may be intentionally (or not) awkward considering in most functional languages it is ideal to pattern-match a tuple instead of accessing it by its index. Since Rust is also imperative, syntax like a.10 can be a good reminder to pattern-match or "go use a struct" already.

提交回复
热议问题