Skip to content

Commit 2137254

Browse files
committed
docs: Add section on constants to tutorial
1 parent aca2419 commit 2137254

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

doc/tutorial.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -463,6 +463,41 @@ character, such as `\n`, `\r`, and `\t`. String literals,
463463
written between double quotes, allow the same escape sequences. Rust strings
464464
may contain newlines.
465465

466+
## Constants
467+
468+
Compile-time constants are declared with `const`. All scalar types,
469+
like integers and floats, may be declared `const`, as well as fixed
470+
length vectors, static strings (more on this later), and structs.
471+
Constants may be declared in any scope and may refer to other
472+
constants. Constant declarations are not type inferred, so must always
473+
have a type annotation. By convention they are written in all capital
474+
letters.
475+
476+
~~~
477+
// Scalars can be constants
478+
const MY_PASSWORD: int = 12345;
479+
480+
// Scalar constants can be combined with other constants
481+
const MY_DOGGIES_PASSWORD: int = MY_PASSWORD + 1;
482+
483+
// Fixed-length vectors
484+
const MY_VECTORY_PASSWORD: [int * 5] = [1, 2, 3, 4, 5];
485+
486+
// Static strings
487+
const MY_STRINGY_PASSWORD: &static/str = "12345";
488+
489+
// Structs
490+
struct Password {
491+
value: int
492+
}
493+
494+
const MY_STRUCTY_PASSWORD: Password = Password { value: MY_PASSWORD };
495+
~~~
496+
497+
> ***Note:*** Support for compile-time constants and constant
498+
> evaluation is essentially added 'as needed'. You may find that
499+
> things you expect to work do not.
500+
466501
## Operators
467502

468503
Rust's set of operators contains very few surprises. Arithmetic is done with

0 commit comments

Comments
 (0)