Rust (programming language): Difference between revisions

Content deleted Content added
OAbot (talk | contribs)
m Open access bot: url-access=subscription, hdl, arxiv, doi updated in citation with #oabot.
these are super verbose and does not accurately represent the majority of Rust code out there
Line 141:
<syntaxhighlight lang="rust">
fn main() {
let foo: i32 = 10;
println!("The value of foo is {foo}");
}
Line 151:
fn main() {
// This code would not compile without adding "mut".
let mut foo: i32 = 10;
println!("The value of foo is {foo}");
foo = 20;
Line 162:
<syntaxhighlight lang="rust">
fn main() {
let foo: i32 = 10;
// This will output "The value of foo is 10"
println!("The value of foo is {foo}");
let foo: i32 = foo * 2;
// This will output "The value of foo is 20"
println!("The value of foo is {foo}");
Line 175:
<syntaxhighlight lang="rust">
fn main() {
let letters: str = "abc";
let letters: usize = letters.len();
}
</syntaxhighlight>
Line 186:
<syntaxhighlight lang="rust">
fn main() {
let x: i32 = {
println!("this is inside the block");
1 + 2
Line 208:
<syntaxhighlight lang="rust">
fn main() {
let x: i32 = 10;
if x > 5 {
println!("value is greater than five");
Line 227:
<syntaxhighlight lang="rust">
fn main() {
let x: i32 = 10;
let new_x: i32 = if x % 2 == 0 { x / 2 } else { 3 * x + 1 };
println!("{new_x}");
}
Line 239:
fn main() {
// Iterate over all integers from 4 to 10
let mut value: i32 = 4;
while value <= 10 {
println!("value = {value}");
Line 276:
<syntaxhighlight lang="rust">
fn main() {
let value: i32 = 456;
let mut x: i32 = 1;
let y = loop {
x *= 10;
Line 286:
println!("largest power of ten that is smaller than or equal to value: {y}");
 
let mut up: i32 = 1;
'outer: loop {
let mut down: i32 = 120;
loop {
if up > 100 {
Line 350:
let tuple: (u32, bool) = (3, true);
let array: [i8; 5] = [1, 2, 3, 4, 5];
let value: bool = tuple.1; // true
let value: i8 = array[2]; // 3
</syntaxhighlight>
 
Line 372:
 
fn main() {
let s: String = String::from("Hello, World");
print_string(s); // s consumed by print_string
// s has been moved, so cannot be used any more
Line 387:
 
fn main() {
let s: String = String::from("Hello, World");
print_string(&s); // s borrowed by print_string
print_string(&s); // s has not been consumed; we can call the function many times
Line 406:
<syntaxhighlight lang="rust">
fn main() {
let x: i32 = 5; // ------------------+- Lifetime 'a
// |
let r: &i32 = &x; // -+-- Lifetime 'b |
// | |
println!("r: {}", r); // | |
Line 420:
<syntaxhighlight lang="rust">
fn main() {
let r: &i32; // ------------------+- Lifetime 'a
// |
{ // |
let x: i32 = 5; // -+-- Lifetime 'b |
r = &x; // ERROR: x does | |
} // not live long -| |
Line 581:
 
fn main() {
let x: i32 = sum!(1, 2, 3);
println!("{x}"); // prints 6
}