Infosec.Pub
  • Communities
  • Create Post
  • Create Community
  • heart
    Support Lemmy
  • search
    Search
  • Login
  • Sign Up
amargo85 to Rust Programming@lemmy.mlEnglish · 2 years ago

Exploring control structures and data types in Rust

chat-to.dev

external-link
message-square
0
link
fedilink
1
external-link

Exploring control structures and data types in Rust

chat-to.dev

amargo85 to Rust Programming@lemmy.mlEnglish · 2 years ago
message-square
0
link
fedilink
First, let's discuss control structures in Rust. 1. **If Expressions**: The syntax for an if expression is similar to other C-like languages. The conditional is followed by a block of code for the true branch. Let's try a simple example: ```rust fn main() { let x = 5; if x > 1 { println!("x is greater than 1"); } } ``` You can also add an optional else branch to handle the false case. ```rust fn main() { let x = 5; if x > 1 { println!("x is greater than 1"); } else { println!("x is not greater than 1"); } } ``` 2. **Loops**: Rust offers several looping constructs, including loops that iterate over a sequence, loop, while, and for. * **Loop**: A basic **loop** with a break statement to exit. ```rust fn main() { let mut counter = 0; loop { if counter == 10 { break; } counter += 1; println!("counter = {}", counter); } } ``` * **While**: A **while** loop, similar to loops in other C-like languages. ```rust fn main() { let mut number = 3; while number != 0 { println!("{}!", number); number -= 1; } println!("LIFTOFF!!!"); } ``` * **For**: A **for** loop is used to iterate over collections, such as arrays, slices, and vectors. ```rust fn main() { let a = [10, 20, 30, 40, 50]; for element in a.iter() { println!("the value is: {}", element); ``` liked the content? then leave your comment or handshake on the post. thanks
alert-triangle
You must log in or # to comment.

Rust Programming@lemmy.ml

rust@lemmy.ml

Subscribe from Remote Instance

Create a post
You are not logged in. However you can subscribe from another Fediverse account, for example Lemmy or Mastodon. To do this, paste the following into the search field of your instance: !rust@lemmy.ml
Visibility: Public
globe

This community can be federated to other instances and be posted/commented in by their users.

  • 2 users / day
  • 2 users / week
  • 2 users / month
  • 6 users / 6 months
  • 80 local subscribers
  • 8.14K subscribers
  • 247 Posts
  • 688 Comments
  • Modlog
  • mods:
  • nutomic@lemmy.ml
  • Joe@lemmy.ml
  • AgreeableLandscape@lemmy.ml
  • BE: 0.19.17
  • Modlog
  • Instances
  • Docs
  • Code
  • join-lemmy.org