0% found this document useful (0 votes)
25 views1 page

Constants - Rust by Example

Uploaded by

Vladimír Pilát
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views1 page

Constants - Rust by Example

Uploaded by

Vladimír Pilát
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

constants - Rust By Example 09.10.

2023 12:55

constants
Rust has two different types of constants which can be declared in any scope including
global. Both require explicit type annotation:

const : An unchangeable value (the common case).


static : A possibly mut able variable with 'static lifetime. The static lifetime is
inferred and does not have to be specified. Accessing or modifying a mutable static
variable is unsafe .

1 // Globals are declared outside all other scopes.


2 static LANGUAGE: &str = "Rust";
3 const THRESHOLD: i32 = 10;
4
5 fn is_big(n: i32) -> bool {
6 // Access constant in some function
7 n > THRESHOLD
8 }
9
10 fn main() {
11 let n = 16;
12
13 // Access constant in the main thread
14 println!("This is {}", LANGUAGE);
15 println!("The threshold is {}", THRESHOLD);
16 println!("{} is {}", n, if is_big(n) { "big" } else { "small" });
17
18 // Error! Cannot modify a `const`.
19 THRESHOLD = 5;
20 // FIXME ^ Comment out this line
21 }

See also:

The const / static RFC, 'static lifetime

https://doc.rust-lang.org/rust-by-example/custom_types/constants.html Stránka 1 z 1

You might also like