mirror of
https://github.com/carbon-language/carbon-lang.git
synced 2026-10-05 14:01:05 +01:00
Document our practices around using auto and naming variable types (#5663)
We use `auto` for most local variables, and we put the type name into the variable name in common cases, especially for our ID types. This was discussed in `#style`: https://discord.com/channels/655572317891461132/821113559755784242/1380091326900469801
This commit is contained in:
@@ -16,6 +16,7 @@ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
|
||||
- [General naming rules](#general-naming-rules)
|
||||
- [File names](#file-names)
|
||||
- [Syntax and formatting](#syntax-and-formatting)
|
||||
- [Naming variable types and the use of `auto`](#naming-variable-types-and-the-use-of-auto)
|
||||
- [Copyable and movable types](#copyable-and-movable-types)
|
||||
- [Static and global variables](#static-and-global-variables)
|
||||
- [Foundational libraries and data types](#foundational-libraries-and-data-types)
|
||||
@@ -197,6 +198,22 @@ these.
|
||||
`protected`. This is motivated by the
|
||||
`misc-non-private-member-variables-in-classes` tidy check.
|
||||
|
||||
### Naming variable types and the use of `auto`
|
||||
|
||||
We generally use `auto` for most local variables when a type can be inferred,
|
||||
except for primitive types such as `bool` and `int`. It is not required to use
|
||||
`auto`, and shorter type names such as `SemIR::InstId` are sometimes named even
|
||||
though they could be inferred. Naming the type can be helpful in cases where the
|
||||
type would be obscure and can not be explained with the variable name. Function
|
||||
parameters generally name the type of each parameter, though lambdas may use
|
||||
`auto` if it's helpful.
|
||||
|
||||
When naming variables, we typically suffix `_id` for ID types. When needed, we
|
||||
can also resolve ambiguity by referring to the full type name in the variable
|
||||
name; for example, if there's a `ClassId`, `InstId`, and `TypeId` for the same
|
||||
class entity, we might call these `class_id`, `class_inst_id`, and
|
||||
`class_type_id`. Similarly, we might call an `Inst` `class_inst`.
|
||||
|
||||
### Copyable and movable types
|
||||
|
||||
- Types should have value semantics and support both move and copy where
|
||||
|
||||
Reference in New Issue
Block a user