From 213725407b8f70dfe9f45d636f759a8ccd9451ca Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Thu, 4 Oct 2012 19:36:56 -0700 Subject: [PATCH] docs: Add section on constants to tutorial --- doc/tutorial.md | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/doc/tutorial.md b/doc/tutorial.md index 7ed93e47a68..a7e627fa08e 100644 --- a/doc/tutorial.md +++ b/doc/tutorial.md @@ -463,6 +463,41 @@ character, such as `\n`, `\r`, and `\t`. String literals, written between double quotes, allow the same escape sequences. Rust strings may contain newlines. +## Constants + +Compile-time constants are declared with `const`. All scalar types, +like integers and floats, may be declared `const`, as well as fixed +length vectors, static strings (more on this later), and structs. +Constants may be declared in any scope and may refer to other +constants. Constant declarations are not type inferred, so must always +have a type annotation. By convention they are written in all capital +letters. + +~~~ +// Scalars can be constants +const MY_PASSWORD: int = 12345; + +// Scalar constants can be combined with other constants +const MY_DOGGIES_PASSWORD: int = MY_PASSWORD + 1; + +// Fixed-length vectors +const MY_VECTORY_PASSWORD: [int * 5] = [1, 2, 3, 4, 5]; + +// Static strings +const MY_STRINGY_PASSWORD: &static/str = "12345"; + +// Structs +struct Password { + value: int +} + +const MY_STRUCTY_PASSWORD: Password = Password { value: MY_PASSWORD }; +~~~ + +> ***Note:*** Support for compile-time constants and constant +> evaluation is essentially added 'as needed'. You may find that +> things you expect to work do not. + ## Operators Rust's set of operators contains very few surprises. Arithmetic is done with