I was doing this for #851 initially, but I think #438 and #826 hadn't made it in (possibly intentionally due to #851? I don't recall). Co-authored-by: Chandler Carruth <chandlerc@gmail.com> Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2.5 KiB
Variables
Table of contents
Overview
Carbon's local variable syntax is:
varidentifier:< expression |auto> [=value ];
Blocks introduce nested scopes and can contain local variable declarations that work similarly to function parameters.
For example:
fn Foo() {
var x: i32 = 42;
}
This introduces a local variable named x into the block's scope. It has the
type Int and is initialized with the value 42. These variable declarations
(and function declarations) have a lot more power than what we're covering just
yet, but this gives you the basic idea.
If auto is used in place of the type, type inference is
used to automatically determine the variable's type.
While there can be global constants, there are no global variables.
Notes
TODO: Constant syntax is an ongoing discussion.
Global variables
We are exploring several different ideas for how to design less bug-prone patterns to replace the important use cases programmers still have for global variables. We may be unable to fully address them, at least for migrated code, and be forced to add some limited form of global variables back. We may also discover that their convenience outweighs any improvements afforded.
Alternatives considered
- No
varintroducer keyword - Name of the
varstatement introducer - Colon between type and identifier
- Type elision
- Type ordering
- Elide the type instead of using
auto
References
- Proposal
#339:
varstatement - Proposal
#618:
varordering - Proposal #851: auto keyword for vars