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

Concepts with real-world examples and small practical projects with Rust

chat-to.dev

external-link
message-square
0
link
fedilink
  • cross-posted to:
  • rust@lemmy.world
1
external-link

Concepts with real-world examples and small practical projects with Rust

chat-to.dev

amargo85 to Rust Programming@lemmy.mlEnglish · 2 years ago
message-square
0
link
fedilink
  • cross-posted to:
  • rust@lemmy.world
Create a struct in Rust called **Product** with fields like **name**, **price**, and **quantity**. Then implement methods to calculate the total value of a given product based on the quantity in stock. ```rust struct Product { name: String, price: f64, quantity: u32, } impl Product { // Method for creating a new product fn new(name: String, price: f64, quantity: u32) -> Self { Product { name, price, quantity } } // Method to calculate the total value of the product based on the quantity in stock fn total_value(&self) -> f64 { self.price * self.quantity as f64 } } fn main() { let product = Product::new(String::from("Laptop"), 1000.0, 5); println!("Total value of {} in stock: ${}", product.name, product.total_value()); } ``` In this example, the struct Product has three fields: name (of type String), price (of type f64) and quantity (of type u32). Next, we implement an associated new() method to create a new instance of Product and a total_value() method that calculates the total value of the product by multiplying the price by the quantity in stock. In main(), we exemplify the use of the struct and the methods created.
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