<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Chittaranjan Sethi on Medium]]></title>
        <description><![CDATA[Stories by Chittaranjan Sethi on Medium]]></description>
        <link>https://medium.com/@chittaranjansethi?source=rss-b3de595bd6ec------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*BTA_DQeIv5PwTNjg_KEXBA.jpeg</url>
            <title>Stories by Chittaranjan Sethi on Medium</title>
            <link>https://medium.com/@chittaranjansethi?source=rss-b3de595bd6ec------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 19:17:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chittaranjansethi/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building Web Services with Nginx (Reverse Proxy + Static Content)]]></title>
            <link>https://medium.com/@chittaranjansethi/building-web-services-with-nginx-reverse-proxy-static-content-2359f02c3f29?source=rss-b3de595bd6ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/2359f02c3f29</guid>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[web-server]]></category>
            <category><![CDATA[reverse-proxy]]></category>
            <dc:creator><![CDATA[Chittaranjan Sethi]]></dc:creator>
            <pubDate>Sat, 03 Jan 2026 04:39:40 GMT</pubDate>
            <atom:updated>2026-01-03T04:39:40.629Z</atom:updated>
            <content:encoded><![CDATA[<p>When you build a web service, you usually want a clean, stable front door for your app: handle incoming traffic, serve static files fast, and forward API requests to your backend. That’s exactly where <strong>Nginx</strong> shines.</p><p>Nginx (“engine x”) is an HTTP web server and reverse proxy (and it can also do caching and load balancing).</p><p>Below is a simple, practical setup: Nginx serves static content and proxies API calls to a backend service (like a Flask app running on port 8000).</p><h3>What is a Reverse Proxy?</h3><p>A reverse proxy receives requests from clients and forwards them to your application servers, then returns the response back to the client. This is a common Nginx use case.</p><h3>Setting Up</h3><h3>1) Install Nginx (Ubuntu example)</h3><pre>sudo apt update<br>sudo apt install nginx</pre><p>Start and enable it:</p><pre>sudo systemctl start nginx<br>sudo systemctl enable nginx</pre><h3>2) Verify it’s running</h3><pre>sudo systemctl status nginx</pre><p>If you open your server IP in a browser, you should see the default Nginx welcome page.</p><h3>Building the “Web Service Front Door” with Nginx</h3><p>Let’s assume:</p><ul><li>Your backend API runs at <a href="http://127.0.0.1:8000/">http://127.0.0.1:8000</a></li><li>You want static files from /var/www/myapp</li><li>You want API routes under /api/</li></ul><h3>1) Create a site config</h3><p>Create a new file:</p><pre>sudo nano /etc/nginx/sites-available/myapp</pre><p>Paste this config:</p><pre>server {<br>    listen 80;<br>    server_name _;</pre><pre>    # Serve static content<br>    root /var/www/myapp;<br>    index index.html;</pre><pre>    location / {<br>        try_files $uri $uri/ =404;<br>    }</pre><pre>    # Proxy API requests to backend<br>    location /api/ {<br>        proxy_pass <a href="http://127.0.0.1:8000/;">http://127.0.0.1:8000/;</a><br>        proxy_set_header Host $host;<br>        proxy_set_header X-Real-IP $remote_addr;<br>    }<br>}</pre><p>Why these parts matter:</p><ul><li>location / serves static files directly.</li><li>location /api/ forwards requests to your backend using proxy_pass and sets useful headers. <a href="https://nginx.org/en/docs/http/ngx_http_proxy_module.html?utm_source=chatgpt.com">Nginx</a></li></ul><h3>2) Enable the site</h3><pre>sudo ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled/</pre><h3>3) Test config and reload Nginx</h3><pre>sudo nginx -t<br>sudo systemctl reload nginx</pre><h3>Testing</h3><h3>Test static content</h3><p>Put a simple file in place:</p><pre>echo &quot;Hello from Nginx&quot; | sudo tee /var/www/myapp/index.html</pre><p>Then:</p><pre>curl http://localhost/</pre><h3>Test API proxying</h3><p>If your backend has an endpoint like GET /health, you should be able to call:</p><pre>curl http://localhost/api/healt</pre><p>If that returns your backend response, Nginx is successfully proxying.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2359f02c3f29" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Web Service with Python and PickleDB]]></title>
            <link>https://medium.com/@chittaranjansethi/building-a-web-service-with-python-and-pickledb-5940bb5d5d5b?source=rss-b3de595bd6ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/5940bb5d5d5b</guid>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[web-services]]></category>
            <category><![CDATA[pickledb]]></category>
            <category><![CDATA[flask]]></category>
            <dc:creator><![CDATA[Chittaranjan Sethi]]></dc:creator>
            <pubDate>Fri, 16 Feb 2024 04:32:38 GMT</pubDate>
            <atom:updated>2024-02-16T04:32:38.211Z</atom:updated>
            <content:encoded><![CDATA[<p>Building web services is a common task for developers in today&#39;s interconnected world. Whether you’re creating an API for your mobile app, integrating systems, or simply storing and retrieving data, having a reliable and lightweight solution is essential. In this blog post, we’ll explore how to build a simple web service using Python and PickleDB.</p><p><strong>What is PickleDB?</strong></p><p>PickleDB is a lightweight and simple key-value store for Python. It stores data in a serialized format using Python’s built-in `pickle` module. PickleDB provides a dictionary-like interface for storing and retrieving data, making it perfect for small-scale applications and prototyping.</p><p><strong>Setting Up</strong></p><p>Before we dive into building our web service, let’s make sure we have PickleDB installed. You can install it via pip:</p><blockquote>pip install pickledb</blockquote><p><strong>Building the Web Service</strong></p><p>For this example, let’s create a simple web service that allows users to store and retrieve key-value pairs. We’ll use the Flask micro-framework for creating the web service.</p><p>First, let’s create a new Python file called `<strong>web_service.py</strong>`:</p><blockquote>from flask import Flask, request, jsonify<br>import pickledb</blockquote><blockquote>app = Flask(__name__)<br>db = pickledb.load(‘data.db’, True)</blockquote><blockquote><a href="http://twitter.com/app">@app</a>.route(‘/set’, methods=[‘POST’])<br>def set_key():<br> data = request.get_json()<br> key = data.get(‘key’)<br> value = data.get(‘value’)<br> <br> if key is None or value is None:<br> return jsonify({‘error’: ‘Key and value must be provided’}), 400<br> <br> db.set(key, value)<br> db.dump()<br> return jsonify({‘message’: ‘Key-value pair set successfully’})</blockquote><blockquote><a href="http://twitter.com/app">@app</a>.route(‘/get’, methods=[‘GET’])<br>def get_key():<br> key = request.args.get(‘key’)<br> <br> if key is None:<br> return jsonify({‘error’: ‘Key must be provided’}), 400<br> <br> value = db.get(key)<br> if value is None:<br> return jsonify({‘error’: ‘Key not found’}), 404<br> <br> return jsonify({‘value’: value})</blockquote><blockquote>if __name__ == ‘__main__’:<br> app.run(debug=True)</blockquote><p>In this code:</p><p>- We import Flask and PickleDB.<br>- We create a Flask app and initialize a PickleDB database.<br>- We define two routes: `/set` for setting key-value pairs and `/get` for retrieving values by key.<br>- The `/set` route expects a JSON payload containing the key and value to be set.<br>- The `/get` route expects a query parameter `key` specifying the key whose value needs to be retrieved.<br>- We handle errors such as missing keys or values and key not found scenarios.</p><p><strong>Running the Web Service</strong></p><p>To run the web service, execute the Python file:</p><blockquote>python web_service.py</blockquote><p>This will start the Flask development server, and your web service will be accessible locally at `http://127.0.0.1:5000`.</p><p><strong>Testing the Web Service</strong></p><p>You can use cURL or Postman to interact with the web service. Here are some examples:</p><blockquote># Set a key-value pair<br>curl -X POST -H “Content-Type: application/json” -d ‘{“key”: “name”, “value”: “John”}’ http://127.0.0.1:5000/set</blockquote><blockquote># Get the value of a key<br>curl http://127.0.0.1:5000/get?key=name</blockquote><p><strong>Conclusion</strong></p><p>In this blog post, we’ve seen how to build a simple web service using Python and PickleDB. PickleDB provides a lightweight and easy-to-use solution for storing and retrieving data, making it ideal for small-scale applications and prototyping. With Flask, creating a web service becomes straightforward, allowing you to focus on building your application logic. Experiment with this example and explore further enhancements to suit your specific use case!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5940bb5d5d5b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Web Service with C++: A Step-by-Step Guide]]></title>
            <link>https://blog.devgenius.io/building-a-web-service-with-c-a-step-by-step-guide-c216cf4050d?source=rss-b3de595bd6ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/c216cf4050d</guid>
            <category><![CDATA[cplusplus]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[professional-development]]></category>
            <category><![CDATA[cpp]]></category>
            <dc:creator><![CDATA[Chittaranjan Sethi]]></dc:creator>
            <pubDate>Wed, 05 Jul 2023 03:45:34 GMT</pubDate>
            <atom:updated>2023-07-05T15:17:45.020Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s interconnected world, building robust web services is crucial for enabling seamless communication between different applications and systems. While many web services are commonly developed using languages like Java or Python, C++ can also be a powerful choice for creating high-performance and scalable web services. In this blog post, we will explore how to write a web service using C++, providing you with a step-by-step guide along with code examples.</p><h4>Prerequisites:</h4><p>Before we dive into building the web service, let’s ensure that you have the necessary tools and libraries set up in your development environment. You will need the following:</p><p>1. A C++ compiler (e.g., GCC or Clang)<br>2. Boost C++ Libraries (particularly the Boost.Asio library for networking)<br>3. An understanding of basic C++ concepts, including classes, functions, and networking.</p><h4>Step 1: Setting up the Project Structure</h4><p>To start, create a new directory for your project. Inside this directory, create a source file (e.g., `<em>main.cpp</em>`) where you will write the code for your web service. Additionally, consider making separate files for handling specific functionalities like request parsing, response generation, and database interactions.</p><h4>Step 2: Include Necessary Libraries</h4><p>In your `<em>main.cpp</em>` file, include the required libraries for networking and handling HTTP requests and responses. Here’s an example:</p><pre>#include &lt;iostream&gt;<br>#include &lt;boost/asio.hpp&gt;<br>#include &lt;boost/algorithm/string.hpp&gt;</pre><h4>Step 3: Define a Request Handler</h4><p>Next, define a function to handle incoming HTTP requests. This function will process the request, perform the necessary operations, and generate an appropriate response. Here’s a basic example of a request handler function:</p><pre>std::string handleRequest(const std::string&amp; request) {<br>    // Process the request and generate the response<br>    std::string response = &quot;HTTP/1.1 200 OK\r\n\r\nHello, World!&quot;;<br>    return response;<br>}</pre><h4>Step 4: Set up a TCP Server</h4><p>Now, let’s create a TCP server that listens for incoming requests and passes them to our request handler function. Here’s a snippet that sets up a simple server:</p><pre>void startServer() {<br>    boost::asio::io_context ioContext;<br>    boost::asio::ip::tcp::acceptor acceptor(ioContext, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), 8080));<br>while (true) {<br>    boost::asio::ip::tcp::socket socket(ioContext);<br>    acceptor.accept(socket);<br>    std::array&lt;char, 4096&gt; buffer;<br>    boost::system::error_code error;<br>    size_t bytesRead = socket.read_some(boost::asio::buffer(buffer), error);<br>    std::string request(buffer.data(), bytesRead);<br>    std::string response = handleRequest(request);<br>    boost::asio::write(socket, boost::asio::buffer(response));<br> }<br>}</pre><h4>Step 5: Run the Server</h4><p>Finally, in your `main()` function, call the `startServer()` function to initiate the web service. Here’s an example:</p><pre>int main() {<br> std::cout &lt;&lt; &quot;Starting the web service…\n&quot;;<br> startServer();<br> return 0;<br>}</pre><p>Congratulations! You’ve successfully built a basic web service using C++. By following this step-by-step guide, you’ve learned how to set up a project, handle HTTP requests, and run a TCP server to listen for incoming connections. This is just the beginning, and you can implement many additional features to enhance your web services, such as authentication, routing, and database integration.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c216cf4050d" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/building-a-web-service-with-c-a-step-by-step-guide-c216cf4050d">Building a Web Service with C++: A Step-by-Step Guide</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cpp Object Concept and How It Is Supported in Rust with Code Examples]]></title>
            <link>https://blog.devgenius.io/cpp-object-concept-and-how-it-is-supported-in-rust-with-code-examples-2e4fb924030f?source=rss-b3de595bd6ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e4fb924030f</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[cplusplus]]></category>
            <category><![CDATA[migration]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[rust-programming-language]]></category>
            <dc:creator><![CDATA[Chittaranjan Sethi]]></dc:creator>
            <pubDate>Sat, 24 Jun 2023 04:29:46 GMT</pubDate>
            <atom:updated>2023-06-25T18:29:40.018Z</atom:updated>
            <content:encoded><![CDATA[<p>Object-oriented programming (OOP) is a popular programming paradigm that focuses on the concept of objects. In C++, objects are created by defining classes, which encapsulate data and behavior into a single unit. However, Rust, a modern systems programming language, takes a different approach to achieve similar functionality while providing stronger memory safety guarantees. In this article, we will explore the object concept in C++ and see how it is supported in Rust, with code examples highlighting the similarities and differences between the two languages.</p><h4>C++ Object Concept:</h4><p>In C++, objects are instances of classes, and they hold their own data and member functions. The class definition specifies the structure and behavior of the objects that will be created. Let’s consider a simple example of a class representing a point in a 2D space:</p><pre>class Point {<br>private:<br>    int x;<br>    int y;<br>    <br>public:<br>    Point(int x, int y) : x(x), y(y) {}<br>    <br>    int getX() { return x; }<br>    int getY() { return y; }<br>    <br>    void setX(int x) { this-&gt;x = x; }<br>    void setY(int y) { this-&gt;y = y; }<br>};</pre><p>In the above example, the `Point` class has private member variables `x` and `y`, and public member functions `getX`, `getY`, `setX`, and `setY` to access and modify the point’s coordinates.</p><p><strong>Creating an object in C++ is straightforward:</strong></p><pre>Point p(3, 5);</pre><p>Here, we create a `Point` object named `p` with coordinates (3, 5).</p><h4>Rust’s Approach to Objects:</h4><p>Rust takes a different approach to achieve encapsulation and data abstraction without the traditional class-based objects found in languages like C++. Instead, Rust uses structs and traits to build reusable and modular components. Structs define the data, while traits define behavior.</p><p>Let’s rewrite the previous `Point` example in Rust:</p><pre>struct Point {<br> x: i32,<br> y: i32,<br>}<br>impl Point {<br> fn new(x: i32, y: i32) -&gt; Self {<br> Point { x, y }<br> }<br> <br> fn get_x(&amp;self) -&gt; i32 {<br> self.x<br> }<br> <br> fn get_y(&amp;self) -&gt; i32 {<br> self.y<br> }<br> <br> fn set_x(&amp;mut self, x: i32) {<br> self.x = x;<br> }<br> <br> fn set_y(&amp;mut self, y: i32) {<br> self.y = y;<br> }<br>}</pre><p>In Rust, we define a struct called `Point`, similar to a class in C++, and implement methods for that struct using the `impl` block. The `new` method serves as a constructor, creating and returning a new instance of the struct. The `&amp;self` and `&amp;mut self` references are used to define methods that borrow or mutably borrow the struct, respectively.</p><p><strong>Creating an object in Rust is done as follows:</strong></p><pre>let p = Point::new(3, 5);</pre><p>In this case, we create a `Point` object named `p` with coordinates (3, 5).</p><h4>Comparing C++ and Rust Objects:</h4><p>Although the syntax and mechanisms differ between C++ and Rust, the underlying concepts of objects are supported in both languages. Both C++ and Rust allow data encapsulation and provide member functions (methods) to operate on the data. However, there are some differences worth noting.</p><p><strong>1. Visibility:</strong><br> — C++ uses access specifiers (`<strong>private</strong>`, `<strong>public</strong>`, `<strong>protected</strong>`) to control visibility, while Rust uses the `<strong>pub</strong>` keyword to denote public visibility by default.<br> — In C++, private members are accessible only within the class, while in Rust, non-public members are not accessible outside the module.<br> <br><strong>2. Mutability:</strong><br> — In C++, member functions can modify member variables by default. In Rust, methods must explicitly define whether they need mutable access to the struct using `&amp;mut self`.<br> — Rust’s approach enforces stronger guarantees on immutability and prevents accidental modification of data.</p><p><strong>3. Inheritance and Polymorphism:</strong><br> — C++ supports inheritance and polymorphism through class hierarchies and virtual functions. Rust, on the other hand, uses traits and trait objects for similar functionality.<br> — Rust’s traits allow for defining shared behavior among types without a strict hierarchy.</p><h4>Conclusion:</h4><p>While C++ follows a class-based object model, Rust approaches objects differently by utilizing structs and traits. Rust’s focus on memory safety, ownership, and borrowing, combined with its strong type system, ensures more robust and secure code. By understanding the object concept in both languages, developers can leverage their respective features to write clean, maintainable, and safe code. It’s worth noting that the code examples provided in this article are simplified for illustrative purposes and may not cover all the complexities and features of C++ and Rust object-oriented programming.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e4fb924030f" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/cpp-object-concept-and-how-it-is-supported-in-rust-with-code-examples-2e4fb924030f">Cpp Object Concept and How It Is Supported in Rust with Code Examples</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web Development with Rust: Harnessing the Power of a Systems Programming Language]]></title>
            <link>https://medium.com/rust-developers/web-development-with-rust-harnessing-the-power-of-a-systems-programming-language-4e73ac82af43?source=rss-b3de595bd6ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e73ac82af43</guid>
            <category><![CDATA[rustlang]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[rust-programming-language]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Chittaranjan Sethi]]></dc:creator>
            <pubDate>Sat, 17 Jun 2023 17:49:36 GMT</pubDate>
            <atom:updated>2023-06-17T17:49:36.623Z</atom:updated>
            <content:encoded><![CDATA[<p>In the world of web development, choosing the right programming language can significantly impact the efficiency, performance, and security of your applications. While languages like JavaScript, Python, and Ruby have traditionally dominated the web development landscape, a new contender has emerged — Rust. Renowned for its memory safety guarantees, performance, and concurrent programming capabilities, Rust is rapidly gaining popularity among developers seeking robust and reliable solutions. In this blog post, we will explore the benefits of using Rust for web development and delve into a code example to showcase its power.</p><h4>Why Rust for Web Development?</h4><p><strong>1. Memory Safety:</strong> Rust’s strong ownership and borrowing system ensures memory safety without sacrificing performance. It eliminates common issues like null pointer dereferences, buffer overflows, and data races, making web applications more secure and less prone to crashes.</p><p><strong>2. Performance:</strong> Rust is designed to be a systems programming language, offering low-level control over system resources. It&#39;s zero-cost abstractions and efficient memory management enable developers to build high-performance web applications that can handle heavy workloads and scale effectively.</p><p><strong>3. Concurrency: </strong>With the rise of multi-core processors, concurrent programming is becoming increasingly important. Rust’s ownership model and built-in concurrency primitives, such as channels and async/await syntax, facilitate writing concurrent code that is safe, efficient, and easy to reason about.</p><p><strong>4. Ecosystem and Tooling: </strong>Rust boasts a growing ecosystem of libraries and frameworks dedicated to web development. Tools like Rocket, Actix, and Tide provide frameworks for building web servers and APIs, while libraries such as <em>reqwest</em> and <em>serde </em>enable seamless integration with external services and data serialization.</p><h4>Code Example: Building a Simple Web Server</h4><p>To illustrate Rust’s capabilities in web development, let’s walk through an example of building a basic web server using the Rocket framework. Rocket is a powerful, intuitive, and type-safe framework that allows you to quickly create robust web applications.</p><h4>Step 1: Setting up the Project</h4><p>First, ensure that Rust and Cargo, Rust’s package manager, are installed on your system. Create a new directory for your project and initialize it with Cargo:</p><pre>$ cargo init rust_web_server<br>$ cd rust_web_server</pre><h4>Step 2: Adding Dependencies</h4><p>Open the `<strong><em>Cargo.toml</em></strong>` file and add the necessary dependencies. In this example, we’ll use Rocket and its async runtime Tokio:</p><pre>[dependencies]<br>rocket = &quot;0.5.0-rc.1&quot;<br>tokio = { version = &quot;1&quot;, features = [&quot;full&quot;] }</pre><h4>Step 3: Creating the Web Server</h4><p>Next, create a new file called `main.rs` and add the following code:</p><pre>#[macro_use]<br>extern crate rocket;<br>#[get(&quot;/&quot;)]<br>fn index() -&gt; &amp;&#39;static str {<br> &quot;Hello, Rust Web Server!&quot;<br>}<br>#[launch]<br>fn rocket() -&gt; _ {<br> rocket::build().mount(&quot;/&quot;, routes![index])<br>}</pre><p>This code defines a simple Rocket server with a single route (“/”) that returns the “Hello, Rust Web Server!” message.</p><h4>Step 4: Running the Web Server</h4><p>To run the web server, use the following command:</p><pre>$ cargo run</pre><p>You should see the server starting and listening on `<strong><em>http://localhost:8000</em></strong>`. Visit that URL in your browser, and you should see the “<em>Hello, Rust Web Server!</em>” message.</p><p>Rust brings the power of systems programming to web development, offering memory safety, performance, and concurrent programming capabilities. Its growing ecosystem of libraries and frameworks makes it an attractive choice for building robust and scalable web applications. In this blog post, we explored the benefits of using Rust for web development and provided a code example showcasing the creation of a simple web server using the Rocket framework. Whether you’re developing APIs, web services, or full-fledged applications, Rust provides a solid foundation for your web development needs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e73ac82af43" width="1" height="1" alt=""><hr><p><a href="https://medium.com/rust-developers/web-development-with-rust-harnessing-the-power-of-a-systems-programming-language-4e73ac82af43">Web Development with Rust: Harnessing the Power of a Systems Programming Language</a> was originally published in <a href="https://medium.com/rust-developers">Rust Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Asynchronous Programming with Rust: A Practical Guide]]></title>
            <link>https://blog.devgenius.io/exploring-asynchronous-programming-with-rust-a-practical-guide-15bac9f56937?source=rss-b3de595bd6ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/15bac9f56937</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[rust-programming-language]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[rustlang]]></category>
            <dc:creator><![CDATA[Chittaranjan Sethi]]></dc:creator>
            <pubDate>Sat, 17 Jun 2023 04:29:12 GMT</pubDate>
            <atom:updated>2023-06-19T19:51:17.827Z</atom:updated>
            <content:encoded><![CDATA[<p>Asynchronous programming is a crucial aspect of modern software development, enabling high-performance and responsive applications. Rust, renowned for its emphasis on memory safety and performance, offers robust tools and abstractions to tackle asynchronous programming challenges. In this blog post, we will delve into the fundamentals of asynchronous programming in Rust, accompanied by a code example, to demonstrate how it facilitates concurrency and boosts application performance.</p><h4>Understanding Asynchronous Programming:</h4><p>Asynchronous programming allows the concurrent execution of tasks without blocking the main thread. It is particularly beneficial for operations involving I/O or other activities that introduce latency, as it maximizes resource utilization and responsiveness.</p><h4>Key Concepts in Rust’s Asynchronous Programming Model:</h4><p><strong>1. Futures: </strong>In Rust, futures represent asynchronous computations that may not have been completed yet. They act as placeholders for eventual results, allowing other tasks to progress while awaiting completion. The<em> `futures`</em> crate provides the necessary abstractions to work with futures in Rust.</p><p><strong>2. Async/Await Syntax: </strong>Rust introduces the <em>`async`</em> and <em>`await`</em> keywords, simplifying the handling of asynchronous code. By marking a function as <em>`async`</em>, you can use the <em>`await`</em> keyword to wait for the completion of a future. This syntax enables writing asynchronous code that resembles synchronous code, enhancing readability and maintainability.</p><p><strong>3. Tokio:</strong> Tokio is a popular asynchronous runtime for Rust, offering a comprehensive set of tools for building efficient and scalable asynchronous applications. It leverages an event-driven model, allowing for effective management of I/O operations and task scheduling.</p><p><strong>4. Channels:</strong> Rust’s standard library includes the <em>`std::sync::mpsc`</em> module, which provides multiple-producer, single-consumer channels. Channels enable asynchronous communication between different parts of the code by sending and receiving messages. They are useful for sharing data and coordinating concurrent operations.</p><p><strong><em>Code Example: Fetching Data Asynchronously</em></strong><br>Let’s explore a practical code example that demonstrates how to use asynchronous programming in Rust to fetch data from multiple endpoints concurrently using the <em>`reqwest`</em> crate and Tokio.</p><pre>use reqwest::Result;<br>use tokio::time::Duration;<br><br>async fn fetch_data(url: &amp;str) -&gt; Result&lt;String&gt; {<br>    // Simulate latency<br>    tokio::time::sleep(Duration::from_secs(1)).await;<br>    <br>    // Fetch data from the given URL<br>    let response = reqwest::get(url).await?;<br>    let body = response.text().await?;<br>    <br>    Ok(body)<br>}<br><br>#[tokio::main]<br>async fn main() -&gt; Result&lt;()&gt; {<br>    let urls = vec![<br>        &quot;https://example.com/api/endpoint1&quot;,<br>        &quot;https://example.com/api/endpoint2&quot;,<br>        &quot;https://example.com/api/endpoint3&quot;,<br>    ];<br><br>    let mut tasks = Vec::new();<br><br>    for url in urls {<br>        let task = tokio::spawn(async move {<br>            let data = fetch_data(url).await?;<br>            println!(&quot;Data fetched: {}&quot;, data);<br>            Result::&lt;()&gt;::Ok(())<br>        });<br><br>        tasks.push(task);<br>    }<br><br>    // Await all tasks to complete<br>    for task in tasks {<br>        task.await?;<br>    }<br><br>    Ok(())<br>}</pre><p>In this code example, we define the `fetch_data` function that fetches data asynchronously from a given URL. We simulate latency using `tokio::time::sleep` to emphasize the asynchronous behavior. The `main` function spawns multiple asynchronous tasks using `tokio::spawn`, each fetching data from a different URL concurrently. Finally, we await the completion of all tasks using a loop.</p><h4>Conclusion:</h4><p>Rust’s asynchronous programming capabilities, facilitated by futures, the async/await syntax, Tokio, and channels, empower developers to create high-performance, concurrent applications. By leveraging these features, Rust ensures memory safety, robustness, and scalability. The code example provided demonstrates the practical implementation of asynchronous programming in Rust, illustrating its potential for building efficient and responsive software solutions. Embrace Rust’s asynchronous programming model and unlock the full potential of concurrent application development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15bac9f56937" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/exploring-asynchronous-programming-with-rust-a-practical-guide-15bac9f56937">Exploring Asynchronous Programming with Rust: A Practical Guide</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Converting `unique_ptr` from C++ to Rust: A Comprehensive Guide with Examples]]></title>
            <link>https://medium.com/rust-developers/converting-unique-ptr-from-c-to-rust-a-comprehensive-guide-with-examples-fa8fb70049a2?source=rss-b3de595bd6ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa8fb70049a2</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[cplusplus]]></category>
            <category><![CDATA[rust-programming-language]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[rustlan]]></category>
            <dc:creator><![CDATA[Chittaranjan Sethi]]></dc:creator>
            <pubDate>Tue, 13 Jun 2023 02:39:28 GMT</pubDate>
            <atom:updated>2023-06-13T02:39:28.705Z</atom:updated>
            <content:encoded><![CDATA[<p>Rust is a modern systems programming language that emphasizes safety, performance, and concurrency. If you’re familiar with C++ and have worked with smart pointers, you may be wondering how to convert C++’s <strong>`unique_ptr`</strong> into its Rust equivalent. In this blog post, we’ll provide a comprehensive guide to help you understand and effectively translate <strong>`unique_ptr`</strong> concepts from C++ to Rust, along with practical examples.</p><h4>Understanding `unique_ptr` in C++:</h4><p>In C++, <strong>`unique_ptr`</strong> is a smart pointer that ensures exclusive ownership of a dynamically allocated resource. It guarantees that only one <strong>`unique_ptr`</strong> can point to the resource at any given time, and when the `<strong>unique_ptr</strong>` goes out of scope or is explicitly reset, it automatically releases the owned resource. This makes <strong>`unique_ptr`</strong> an excellent choice for managing resources that need explicit deallocation.</p><h4>Equivalent in Rust: `Box`</h4><p>In Rust, the equivalent of <strong>`unique_ptr` </strong>is the<strong> `Box`</strong> type. It provides exclusive ownership of heap-allocated memory and automatically cleans up the resource when it goes out of scope. <strong>`Box`</strong> is extensively used in Rust for managing memory and resources.</p><h4>Converting `unique_ptr` to `Box`:</h4><p>Let’s explore a few examples to demonstrate the process of converting <strong>`unique_ptr`</strong> code to Rust’s <strong>`Box`</strong>.</p><p><strong>Example 1: Basic `unique_ptr` conversion</strong><br><strong>C++ code:</strong></p><pre>#include &lt;memory&gt;<br>int main() {<br> std::unique_ptr&lt;int&gt; ptr(new int(42));<br> // …<br> return 0;<br>}</pre><p><strong>Rust equivalent:</strong></p><pre>fn main() {<br> let ptr = Box::new(42);<br> // …<br>}</pre><p><strong>Example 2: `unique_ptr` with custom deleter</strong><br><strong>C++ code:</strong></p><pre>#include &lt;memory&gt;<br>#include &lt;iostream&gt;<br>struct CustomDeleter {<br> void operator()(int* ptr) {<br> std::cout &lt;&lt; &quot;Custom deleter called&quot; &lt;&lt; std::endl;<br> delete ptr;<br> }<br>};<br>int main() {<br> std::unique_ptr&lt;int, CustomDeleter&gt; ptr(new int(42));<br> // …<br> return 0;<br>}</pre><p><strong>Rust equivalent:</strong></p><pre>struct CustomDeleter;<br>impl Drop for CustomDeleter {<br> fn drop(&amp;mut self) {<br> println!(&quot;Custom deleter called&quot;);<br> }<br>}<br>fn main() {<br> let ptr = Box::new(42);<br> // …<br>}</pre><p><strong>Example 3: `unique_ptr` with arrays</strong><br><strong>C++ code:</strong></p><pre>#include &lt;memory&gt;<br>int main() {<br> std::unique_ptr&lt;int[]&gt; arr(new int[5]);<br> // …<br> return 0;<br>}</pre><p><strong>Rust equivalent:</strong></p><pre>fn main() {<br> let arr = Box::new([0; 5]);<br> // …<br>}</pre><h4>Conclusion:</h4><p>Translating C++ `<strong>unique_ptr</strong>` code to Rust’s `<strong>Box</strong>` is relatively straightforward. By understanding the ownership and memory management principles of both languages, you can effectively convert `<strong>unique_ptr</strong>` code to its Rust equivalent. In this blog post, we covered the basics of converting `<strong>unique_ptr</strong>` to `<strong>Box</strong>` and provided practical examples to guide you through the process.</p><p>Rust’s emphasis on safety and memory management makes it an excellent alternative to C++ for systems programming tasks. By leveraging the power of Rust’s `<strong>Box</strong>` type, you can write robust and memory-safe code while benefiting from its expressive syntax and modern language features.</p><p>Remember, this guide serves as a starting point, and as you gain more experience with Rust, you’ll discover additional techniques and idioms to optimize your code further. Happy coding in Rust!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa8fb70049a2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/rust-developers/converting-unique-ptr-from-c-to-rust-a-comprehensive-guide-with-examples-fa8fb70049a2">Converting `unique_ptr` from C++ to Rust: A Comprehensive Guide with Examples</a> was originally published in <a href="https://medium.com/rust-developers">Rust Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Rust: A Beginner’s Guide to Rust Basics]]></title>
            <link>https://blog.devgenius.io/getting-started-with-rust-a-beginners-guide-to-rust-basics-bd714ce7d1fe?source=rss-b3de595bd6ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd714ce7d1fe</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[rustlang]]></category>
            <category><![CDATA[rust-programming-language]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Chittaranjan Sethi]]></dc:creator>
            <pubDate>Sun, 11 Jun 2023 03:39:08 GMT</pubDate>
            <atom:updated>2023-06-14T17:39:45.949Z</atom:updated>
            <content:encoded><![CDATA[<p>Rust is a modern systems programming language known for its emphasis on memory safety, concurrency, and performance. It combines the low-level control of languages like <strong>C</strong> and <strong>C++</strong> with the safety guarantees of modern programming languages. In this blog post, we will dive into the basics of Rust programming, exploring its key features and providing code examples along the way.</p><h4>1. Installation and Setup:</h4><p>Before we begin, let’s make sure Rust is installed on your system. Head over to the official Rust website (<a href="https://www.rust-lang.org/">https://www.rust-lang.org/</a>) and follow the installation instructions for your specific operating system. Once installed, you can check if Rust is properly set up by opening a terminal and typing:</p><pre>  $ rustc --version </pre><p>If you see the Rust version printed, you’re good to go!</p><h4>2. Hello, World! — Your First Rust Program:</h4><p>Let’s start with the classic “Hello, World!” program. Create a new file named `main.rs` and open it in your favorite text editor. Add the following code:</p><pre>fn main() {<br> println!(&quot;Hello, World!&quot;);<br>}</pre><p>Save the file and navigate to its directory using the terminal. To compile and run the program, use the following command:</p><pre>$ rustc main.rs<br>$ ./main</pre><p>You should see the output:</p><pre>Hello, World!</pre><p>Congratulations! You have just written and executed your first Rust program.</p><h4>3. Variables and Data Types:</h4><p>Rust is a statically-typed language, meaning variables must have their types declared at compile time. Let’s explore some of the basic data types in Rust:</p><p><strong>- Integer Types:</strong></p><pre>fn main() {<br> let a: u32 = 10; // Unsigned 32-bit integer<br> let b: i64 = -500; // Signed 64-bit integer<br> let c: usize = 100; // Unsigned size-based integer<br>println!(&quot;a: {}, b: {}, c: {}&quot;, a, b, c);<br>}</pre><p><strong>- Floating-Point Types:</strong></p><pre>fn main() {<br> let x: f32 = 3.14; // 32-bit floating-point number<br> let y: f64 = 2.718; // 64-bit floating-point number<br>println!(&quot;x: {}, y: {}&quot;, x, y);<br>}</pre><p><strong>- Boolean Type:</strong></p><pre>fn main() {<br> let is_true: bool = true;<br> let is_false = false; // Type inference<br>println!(&quot;is_true: {}, is_false: {}&quot;, is_true, is_false);<br>}</pre><h4>4. Control Flow:</h4><p>Rust provides control flow structures similar to other programming languages. Let’s look at some examples:</p><p><strong>- If-else Statement:</strong></p><pre>fn main() {<br> let number = 42;<br>if number &gt; 50 {<br> println!(&quot;Greater than 50&quot;);<br> } else if number == 50 {<br> println!(&quot;Equal to 50&quot;);<br> } else {<br> println!(&quot;Less than 50&quot;);<br> }<br>}</pre><p><strong>- Loop:</strong></p><pre>fn main() {<br> let mut counter = 0;<br>loop {<br> println!(&quot;Counter: {}&quot;, counter);<br> counter += 1;<br>if counter == 5 {<br> break;<br> }<br> }<br>}</pre><p><strong>- While Loop:</strong></p><pre>fn main() {<br> let mut counter = 0;<br>while counter &lt; 5 {<br> println!(&quot;Counter: {}&quot;, counter);<br> counter += 1;<br> }<br>}</pre><h4>5. Functions:</h4><p>Functions are fundamental building blocks in Rust. Here’s an example of a function that returns the sum of two numbers:</p><pre>fn add_numbers(a: i32, b: i32) -&gt; i32 {<br> a + b<br>}<br>fn main() {<br> let result = add_numbers(10, 20);<br> println!(&quot;Result: {}&quot;, result);<br>}</pre><h4>6. Conclusion:</h4><p>In this blog post, we covered the basics of Rust programming. We learned how to set up Rust on our system, and wrote a<em> “Hello, World!” </em>The program explored data types, and control flow structures, and created a simple function.</p><p>Rust is a powerful language with much more to offer, including ownership and borrowing, concurrency primitives, and extensive libraries. By mastering the basics, you’ve taken the first step towards unlocking the full potential of Rust.</p><p>I hope this blog post provided you with a solid foundation for your journey into Rust programming. Happy coding!</p><p>Remember, practice makes perfect, so keep experimenting and exploring Rust&#39;s rich ecosystem.</p><h4>Resources:</h4><p>- Official Rust website: <a href="https://www.rust-lang.org/">https://www.rust-lang.org/</a><br>- Rust documentation: <a href="https://doc.rust-lang.org/">https://doc.rust-lang.org/</a><br>- Rust Playground: <a href="https://play.rust-lang.org/">https://play.rust-lang.org/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd714ce7d1fe" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/getting-started-with-rust-a-beginners-guide-to-rust-basics-bd714ce7d1fe">Getting Started with Rust: A Beginner’s Guide to Rust Basics</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From C++ Classes to Rust: A Practical Guide with Code Examples]]></title>
            <link>https://blog.devgenius.io/from-c-classes-to-rust-a-practical-guide-with-code-examples-899395963511?source=rss-b3de595bd6ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/899395963511</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[rustlang]]></category>
            <category><![CDATA[cpp17]]></category>
            <category><![CDATA[cplusplus]]></category>
            <category><![CDATA[rust-programming-language]]></category>
            <dc:creator><![CDATA[Chittaranjan Sethi]]></dc:creator>
            <pubDate>Sat, 10 Jun 2023 15:21:45 GMT</pubDate>
            <atom:updated>2023-06-18T04:55:31.783Z</atom:updated>
            <content:encoded><![CDATA[<p>Rust has emerged as a powerful systems programming language known for its safety features and performance. If you’re coming from a C++ background, understanding how to translate C++ classes into Rust is crucial for a smooth transition. In this blog post, we will walk you through the process of converting C++ classes to Rust, providing code examples to illustrate the concepts and syntax involved.</p><h4>1. C++ Class Basics:</h4><p>In C++, classes serve as the foundation for object-oriented programming. They encapsulate data and behavior within a single unit. Here’s an example of a simple C++ class:</p><pre>class Rectangle {<br>private:<br> int width;<br> int height;<br>public:<br> Rectangle(int w, int h) : width(w), height(h) {}<br>int area() {<br> return width * height;<br> }<br>};</pre><h4>2. Rust Structs:</h4><p>In Rust, structs act as the primary building blocks for defining data structures. Let’s translate the C++ Rectangle class into a Rust struct:</p><pre>struct Rectangle {<br> width: i32,<br> height: i32,<br>}<br>impl Rectangle {<br> fn new(w: i32, h: i32) -&gt; Rectangle {<br> Rectangle {<br> width: w,<br> height: h,<br> }<br> }<br>fn area(&amp;self) -&gt; i32 {<br> self.width * self.height<br> }<br>}</pre><h4>3. Encapsulation and Data Hiding:</h4><p>C++ provides access specifiers (public, private, protected) to control member visibility. In Rust, visibility is controlled by the `pub` keyword. Let’s see an example:</p><pre>mod shapes {<br> pub struct Rectangle {<br> width: i32,<br> height: i32,<br> }<br>impl Rectangle {<br> pub fn new(w: i32, h: i32) -&gt; Rectangle {<br> Rectangle {<br> width: w,<br> height: h,<br> }<br> }<br>pub fn area(&amp;self) -&gt; i32 {<br> self.width * self.height<br> }<br> }<br>}</pre><h4>4. Methods and Associated Functions:</h4><p>C++ member functions can be translated into Rust methods. Additionally, C++ static member functions can be mimicked by associated functions in Rust. Here’s an example:</p><pre>struct Circle {<br> radius: f64,<br>}<br>impl Circle {<br> fn new(radius: f64) -&gt; Circle {<br> Circle { radius }<br> }<br>fn area(&amp;self) -&gt; f64 {<br> std::f64::consts::PI * self.radius * self.radius<br> }<br>}<br>impl Circle {<br> fn from_diameter(diameter: f64) -&gt; Circle {<br> Circle::new(diameter / 2.0)<br> }<br>}</pre><h4>5. Inheritance and Polymorphism:</h4><p>Rust takes a different approach to code reuse and polymorphism compared to C++. Instead of inheritance, Rust promotes composition and trait implementation. Here’s an example:</p><pre>trait Shape {<br> fn area(&amp;self) -&gt; f64;<br>}<br>struct Rectangle {<br> width: f64,<br> height: f64,<br>}<br>impl Shape for Rectangle {<br> fn area(&amp;self) -&gt; f64 {<br> self.width * self.height<br> }<br>}<br>struct Circle {<br> radius: f64,<br>}<br>impl Shape for Circle {<br> fn area(&amp;self) -&gt; f64 {<br> std::f64::consts::PI * self.radius * self.radius<br> }<br>}</pre><p>Conclusion:<br>Translating C++ classes to Rust requires understanding the similarities and differences between the two languages. By examining the provided code examples, you now have a solid foundation for migrating your C++ classes to Rust’s struct-oriented approach. Embrace Rust’s safety guarantees, expressive syntax, and powerful features as you continue your programming journey. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=899395963511" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/from-c-classes-to-rust-a-practical-guide-with-code-examples-899395963511">From C++ Classes to Rust: A Practical Guide with Code Examples</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Converting `shared_ptr` from C++ to Rust: A Comprehensive Guide with Examples]]></title>
            <link>https://blog.devgenius.io/converting-shared-ptr-from-c-to-rust-a-comprehensive-guide-with-examples-39b54ba6c1c0?source=rss-b3de595bd6ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/39b54ba6c1c0</guid>
            <category><![CDATA[cpp11]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[cpplus]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[cpp17]]></category>
            <dc:creator><![CDATA[Chittaranjan Sethi]]></dc:creator>
            <pubDate>Fri, 09 Jun 2023 02:28:10 GMT</pubDate>
            <atom:updated>2023-06-13T09:40:36.633Z</atom:updated>
            <content:encoded><![CDATA[<p>C++ and Rust are both powerful programming languages known for their memory management capabilities. While C++ utilizes smart pointers like <strong>`shared_ptr` </strong>to manage memory, Rust employs a concept called ownership and a feature called <strong>`Rc`</strong> (reference counting) for similar purposes. If you’re transitioning from C++ to Rust and need to convert <strong>`shared_ptr`</strong> usage, this blog post will guide you through the process with a practical example.</p><h4>Example Scenario:</h4><p>Let’s consider a scenario where we have a simple C++ code snippet that uses <strong>`shared_ptr`</strong> to manage a data structure representing a person’s profile:</p><pre>#include &lt;iostream&gt;<br>#include &lt;memory&gt;<br><br>struct Profile {<br>    std::string name;<br>    int age;<br>};<br><br>int main() {<br>    std::shared_ptr&lt;Profile&gt; profilePtr(new Profile{&quot;John Doe&quot;, 25});<br><br>    std::cout &lt;&lt; &quot;Name: &quot; &lt;&lt; profilePtr-&gt;name &lt;&lt; std::endl;<br>    std::cout &lt;&lt; &quot;Age: &quot; &lt;&lt; profilePtr-&gt;age &lt;&lt; std::endl;<br><br>    return 0;<br>}</pre><p>We’ll now walk through the steps to convert the above code into Rust, replacing <strong>`shared_ptr` </strong>with Rust’s <strong>`Rc`</strong>.</p><h4>Step 1: Setting up the Rust Project:</h4><p>First, ensure you have Rust installed on your system. Use <strong>`rustup`</strong> to manage your Rust installation. Create a new Rust project by running the following command in your terminal:</p><pre>$ cargo new shared_ptr_to_rc<br>$ cd shared_ptr_to_rc</pre><h4>Step 2: Define the Rust Equivalent Struct:</h4><p>In Rust, we’ll create a struct that mirrors the <strong>`Profile`</strong> struct from the C++ code. Open the <strong>`src/main.rs`</strong> file and replace its contents with the following:</p><pre>use std::rc::Rc;<br>struct Profile {<br> name: String,<br> age: i32,<br>}</pre><h4>Step 3: Main Function Conversion:</h4><p>Now, let’s convert the <strong>`main` </strong>function. Replace the content of the <strong>`main.rs`</strong> file with the following:</p><pre>fn main() {<br> let profile_rc = Rc::new(Profile {<br> name: String::from(&quot;John Doe&quot;),<br> age: 25,<br> });<br>println!(&quot;Name: {}&quot;, profile_rc.name);<br> println!(&quot;Age: {}&quot;, profile_rc.age);<br>}</pre><h4>Step 4: Testing the Conversion:</h4><p>To test our code, we’ll use the <strong>`cargo run`</strong> command in the terminal:</p><pre>$ cargo run</pre><h4>Expected Output:</h4><pre>Name: John Doe<br>Age: 25</pre><p>By following the steps outlined above, we successfully converted the C++ code that uses <strong>`shared_ptr`</strong> to its equivalent Rust code utilizing <strong>`Rc`</strong>. The Rust <strong>`Rc`</strong> provides the necessary functionality for reference counting and memory management in a safe and idiomatic way.</p><p>Rust’s ownership model and <strong>`Rc`</strong> can help you write reliable, concurrent, and efficient code while ensuring memory safety. Though this example showcases a simple conversion, it demonstrates the basic process for converting <strong>`shared_ptr` </strong>usage from C++ to Rust.</p><p>As you continue your journey with Rust, exploring additional features like <strong>`Arc`</strong> for atomic reference counting or using interior mutability patterns with<strong> `RefCell`</strong> and<strong> `Mutex` </strong>will further expand your Rust programming capabilities.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39b54ba6c1c0" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/converting-shared-ptr-from-c-to-rust-a-comprehensive-guide-with-examples-39b54ba6c1c0">Converting `shared_ptr` from C++ to Rust: A Comprehensive Guide with Examples</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>