From 2b7302a1514818574b1117e84321fc0a5aec536d Mon Sep 17 00:00:00 2001 From: EPetrineLynghaug <136695793+EPetrineLynghaug@users.noreply.github.com> Date: Sun, 19 Jan 2025 14:25:59 +0100 Subject: [PATCH 1/8] Add Rust and Yew case study placeholder --- src/content/docs/rust-and-yew/rust-and-yew.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 src/content/docs/rust-and-yew/rust-and-yew.md diff --git a/src/content/docs/rust-and-yew/rust-and-yew.md b/src/content/docs/rust-and-yew/rust-and-yew.md new file mode 100644 index 000000000..d06641b09 --- /dev/null +++ b/src/content/docs/rust-and-yew/rust-and-yew.md @@ -0,0 +1 @@ +# Rust and Yew Case Study From 65ad8b487dd969aa4f4850f844cef7948ce43ba5 Mon Sep 17 00:00:00 2001 From: EPetrineLynghaug <136695793+EPetrineLynghaug@users.noreply.github.com> Date: Sun, 19 Jan 2025 16:12:25 +0100 Subject: [PATCH 2/8] Started. --- src/content/docs/rust-and-yew/rust-and-yew.md | 93 ++++++++++++++++++- 1 file changed, 92 insertions(+), 1 deletion(-) diff --git a/src/content/docs/rust-and-yew/rust-and-yew.md b/src/content/docs/rust-and-yew/rust-and-yew.md index d06641b09..99fb5197c 100644 --- a/src/content/docs/rust-and-yew/rust-and-yew.md +++ b/src/content/docs/rust-and-yew/rust-and-yew.md @@ -1 +1,92 @@ -# Rust and Yew Case Study +--- +title: Case Study Rust and Yew framework. +author: ELisabeth Petrine Lynghaug +tags: example, case study, platform +--- + +## Introduction + +In this case study, I explore the Rust programming language and the Yew framework. Rust is celebrated for its security, high performance, and memory safety, achieved without relying on garbage collection. Its advanced compiler acts as a code auditor, ensuring correctness and safety before execution. + +The primary goal of this project is to demonstrate Rust's type system and unique features like PhantomData, while integrating a small frontend with Yew and an API using Sanity. I chose Sanity because it is free and quick to set up, allowing me to focus on Rust’s capabilities without needing a self-hosted backend. + +Had I more time, I would have built a backend with Actix, but this would have required paid server resources. Nonetheless, this setup allowed me to stress-test Rust and observe its behavior and complexity in a full-stack context. + +## Brief History + +You may use a bullet point list or subheadings to structure a timeline of your chosen topic's history: +- 2010: Rust is started by Mozilla to build a safer and faster browser engine (Servo). +- 2015: Rust is publicly released. +- 2015-2023: Rust gains traction in system programming and begins to make its mark in web development. +- Present: Rust is used by companies like Discord, Meta, Dropbox, and Figma. The rise of WebAssembly (Wasm) has enabled Rust to be used for both backend and frontend development, with frameworks like Yew showcasing its potential. + +## Main Features of Rust and Yew + +Describe the primary purpose of the tool that you have selected. Which problems does it solve? Is there something unique about this tool? How can it be useful to developers? + +You may use subheadings, tables or bullet points to structure your description: +- **Example Feature:** This feature does something for a specific reason. +- **Example Feature:** This feature does something for a specific reason. +- **Example Feature:** This feature does something for a specific reason. + +Example feature table: + +| Feature | Description | +| --- | --- | +| Memory Safety | Prevents memory errors without garbage collection using the ownership model.| +| Advanced Compiler|Acts as a code auditor, providing detailed error messages for safe coding. | +| Result Type| Ensures explicit error handling, avoiding unnoticed critical errors. | +| Ownership Model| Manages memory through strict ownership rules, ensuring safety and speed. | +| High Performance | Competes with C/C++ for speed while maintaining safety. | + +**Unique Concepts in Rust** +- **PhantomData:** Allows developers to define state in a way that ensures safety and correctness. For instance, it can differentiate between unauthorized and authorized states to prevent accidental access to sensitive functions. +- **Result and Option Types:** Require explicit handling of success and failure cases, reducing runtime errors. + + + +| Feature | Description | +| --- | --- | +| WebAssembly Support |Yew compiles to Wasm, offering better performance and lower resource usage. | +| Reactive UI | Enables modern, reactive user interfaces similar to React but in Rust. | +| Memory Safety | Inherits Rust’s safety and ownership model, reducing runtime errors.| +| Shared Codebase | Allows shared logic between frontend and backend.| +| Tailwind CSS Support | Simplifies styling by integrating with popular tools. | + +**Advantages** +- Faster and more resource-efficient than JavaScript-based frameworks. +- Strong type safety and better error handling. +- Seamless integration with Rust backend systems. + +**Challenges** +- Limited documentation and ecosystem compared to mature frontend frameworks. +- Requires knowledge of both Rust and WebAssembly, making onboarding steeper. + + +## Market Comparison + +This section can be used to compare the advantages and disadvantages of your chosen tool to other similar tools. You may use subheadings, tables or bullet points to structure your description. + +If you are writing about an open source tool, it may be a good idea to compare it to similar proprietary tools. Likewise, if you are writing about a proprietary tool, it may be a good idea to compare it to similar open source tools. + +Similarly, a self hosted tool and a cloud based tool with a similar purpose may make for a good comparison. + +## Getting Started + +If applicable, describe how to get started with your chosen tool. By providing examples, this can help to demystify a tool and make it more accessible to beginners. + +## Conclusion + +This section can be used to summarize your findings. What are the main advantages and disadvantages of your chosen tool? What are the main use cases for this tool? What are the main limitations of this tool? What does the future look like for this tool? + +## References + +- [Example.com](https://example.com) +- *Good Examples* by John Doe, 1990 +- The Example Podcast, Episode 1 +- [Examples Explained](https://youtu.be/dQw4w9WgXcQ) + +## Additional Resources + +- [More about Examples](https://example.com) +- [Examples, the Full Course](https://youtu.be/dQw4w9WgXcQ) \ No newline at end of file From 505b313d27138be805b0247e14352fec85b8b891 Mon Sep 17 00:00:00 2001 From: EPetrineLynghaug <136695793+EPetrineLynghaug@users.noreply.github.com> Date: Sun, 19 Jan 2025 16:38:38 +0100 Subject: [PATCH 3/8] Started. --- src/content/docs/rust-and-yew/rust-and-yew.md | 46 +++++++++++++------ 1 file changed, 32 insertions(+), 14 deletions(-) diff --git a/src/content/docs/rust-and-yew/rust-and-yew.md b/src/content/docs/rust-and-yew/rust-and-yew.md index 99fb5197c..b0f914952 100644 --- a/src/content/docs/rust-and-yew/rust-and-yew.md +++ b/src/content/docs/rust-and-yew/rust-and-yew.md @@ -1,6 +1,6 @@ --- title: Case Study Rust and Yew framework. -author: ELisabeth Petrine Lynghaug +author: ELisabeth Petrine Lynghaug tags: example, case study, platform --- @@ -65,28 +65,46 @@ Example feature table: ## Market Comparison -This section can be used to compare the advantages and disadvantages of your chosen tool to other similar tools. You may use subheadings, tables or bullet points to structure your description. - -If you are writing about an open source tool, it may be a good idea to compare it to similar proprietary tools. Likewise, if you are writing about a proprietary tool, it may be a good idea to compare it to similar open source tools. - -Similarly, a self hosted tool and a cloud based tool with a similar purpose may make for a good comparison. +When comparing Rust and Yew to other technologies, their unique advantages and limitations become evident. Rust offers unparalleled memory safety and performance, making it ideal for developers prioritizing reliability. However, its steep learning curve and strict ownership model may pose challenges for beginners. Yew, while fast and efficient due to WebAssembly, requires knowledge of Rust and has limited documentation, which can slow adoption. In contrast, technologies like JavaScript and React benefit from mature ecosystems but lack the inherent safety and performance of Rust and Yew. ## Getting Started If applicable, describe how to get started with your chosen tool. By providing examples, this can help to demystify a tool and make it more accessible to beginners. +Rust + +Ownership Model: Demands a deep understanding of ownership, borrowing, and lifetimes. + +Strict Typing: Requires careful adherence to type rules, increasing development time initially. + +Growing Ecosystem: While expanding, the ecosystem is not as extensive as other languages. + +Yew + +Steep Learning Curve: Requires knowledge of both Rust and WebAssembly. + +Limited Documentation: Still early in development, making troubleshooting harder. + +Wasm Challenges: Debugging and browser integration can be more complex than JavaScrit + + + ## Conclusion -This section can be used to summarize your findings. What are the main advantages and disadvantages of your chosen tool? What are the main use cases for this tool? What are the main limitations of this tool? What does the future look like for this tool? +Rust + +Rust is a powerful and flexible language that delivers high performance and unparalleled safety. It is ideal for developers prioritizing reliability and correctness, especially in complex systems. + +Yew + +Yew demonstrates that Rust can be a viable alternative for frontend development. While it is still in its early stages, it provides a promising path for full-stack development with Rust, offering better safety and performance than many current technologies. + +Both Rust and Yew require significant time and effort to master, but the results are applications that are faster, safer, and more robust than most alternatives. ## References -- [Example.com](https://example.com) -- *Good Examples* by John Doe, 1990 -- The Example Podcast, Episode 1 -- [Examples Explained](https://youtu.be/dQw4w9WgXcQ) +- [Rust](https://www.rust-lang.org/) +- [Yew](https://yew.rs/) +- [Webassembly](https://webassembly.org/) -## Additional Resources -- [More about Examples](https://example.com) -- [Examples, the Full Course](https://youtu.be/dQw4w9WgXcQ) \ No newline at end of file From 44e8d9197db7fc18b5dba82f8ed2cc5bb6f16a6e Mon Sep 17 00:00:00 2001 From: EPetrineLynghaug <136695793+EPetrineLynghaug@users.noreply.github.com> Date: Sun, 19 Jan 2025 17:10:01 +0100 Subject: [PATCH 4/8] editing intro. --- src/content/docs/rust-and-yew/rust-and-yew.md | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/content/docs/rust-and-yew/rust-and-yew.md b/src/content/docs/rust-and-yew/rust-and-yew.md index b0f914952..75870d45f 100644 --- a/src/content/docs/rust-and-yew/rust-and-yew.md +++ b/src/content/docs/rust-and-yew/rust-and-yew.md @@ -6,11 +6,17 @@ tags: example, case study, platform ## Introduction -In this case study, I explore the Rust programming language and the Yew framework. Rust is celebrated for its security, high performance, and memory safety, achieved without relying on garbage collection. Its advanced compiler acts as a code auditor, ensuring correctness and safety before execution. +Working with Rust has been both a challenge and a joy. It is a language that stands out for its combination of high performance, security, and memory safety—all achieved without relying on garbage collection. Rust’s compiler feels like a collaborator, catching mistakes before they become runtime issues. It's like having a vigilant mentor constantly watching over your code. -The primary goal of this project is to demonstrate Rust's type system and unique features like PhantomData, while integrating a small frontend with Yew and an API using Sanity. I chose Sanity because it is free and quick to set up, allowing me to focus on Rust’s capabilities without needing a self-hosted backend. +The goal of this project was to build a login application that highlights some of Rust's most powerful features: -Had I more time, I would have built a backend with Actix, but this would have required paid server resources. Nonetheless, this setup allowed me to stress-test Rust and observe its behavior and complexity in a full-stack context. +**Strong Typing and Error Handling:** Demonstrating how Rust's type system prevents mistakes and guarantees safety. + +**Frontend Exploration with Yew:** Using Yew, a Rust-based frontend framework, to bring Rust's power into the browser. + +**API Integration via Sanity:** Instead of building a backend from scratch, I used Sanity—a headless CMS—to deliver dynamic content. + +By merging Rust's backend strengths with Yew's frontend capabilities, this project showcases how Rust can be used as a full-stack solution for modern web applications. While time constraints prevented me from delving deeper into custom backend solutions with Actix, the setup with Sanity provided an efficient and reliable alternative. This project not only tested Rust’s capabilities but also pushed my understanding of how a cutting-edge language can integrate across the stack. ## Brief History From 706680c03eda34e2d09b5d592d87eab01db08755 Mon Sep 17 00:00:00 2001 From: EPetrineLynghaug <136695793+EPetrineLynghaug@users.noreply.github.com> Date: Sun, 19 Jan 2025 18:37:08 +0100 Subject: [PATCH 5/8] editing intro. --- src/content/docs/rust-and-yew/rust-and-yew.md | 180 ++++++++++++------ 1 file changed, 118 insertions(+), 62 deletions(-) diff --git a/src/content/docs/rust-and-yew/rust-and-yew.md b/src/content/docs/rust-and-yew/rust-and-yew.md index 75870d45f..548479c4d 100644 --- a/src/content/docs/rust-and-yew/rust-and-yew.md +++ b/src/content/docs/rust-and-yew/rust-and-yew.md @@ -1,116 +1,172 @@ --- -title: Case Study Rust and Yew framework. -author: ELisabeth Petrine Lynghaug +title: Case Study Rust and Yew Framework +author: Elisabeth Petrine Lynghaug tags: example, case study, platform --- ## Introduction -Working with Rust has been both a challenge and a joy. It is a language that stands out for its combination of high performance, security, and memory safety—all achieved without relying on garbage collection. Rust’s compiler feels like a collaborator, catching mistakes before they become runtime issues. It's like having a vigilant mentor constantly watching over your code. +Working with Rust has been both a challenge and a joy. Rust is a modern programming language renowned for its security, high performance, and memory safety—achieved without a garbage collector. Originally developed by Mozilla to build a faster and safer browser engine (Servo), Rust stands out thanks to its **ownership model**, which automatically manages memory and prevents common errors like data races and memory leaks. -The goal of this project was to build a login application that highlights some of Rust's most powerful features: +The goal of this project was to build a login application that illustrates how Rust can be used in a full-stack environment: -**Strong Typing and Error Handling:** Demonstrating how Rust's type system prevents mistakes and guarantees safety. +- **Strong Typing and Error Handling:** Showcasing how Rust’s type system prevents errors and guarantees safety. +- **Frontend Exploration with Yew:** Leveraging Yew, a Rust-based framework compiled to WebAssembly, to write frontend logic in Rust. +- **API Integration via Sanity:** Instead of creating a custom backend (e.g., using Actix), Sanity (a headless CMS) was used to deliver dynamic content. -**Frontend Exploration with Yew:** Using Yew, a Rust-based frontend framework, to bring Rust's power into the browser. +By combining Rust’s backend strengths with Yew’s frontend capabilities, this project highlights how Rust can serve as an end-to-end tool for modern application development. Although time constraints meant I did not implement a custom backend in Rust, using Sanity provided a reliable and efficient alternative. Throughout this project, I challenged my own understanding of Rust and discovered how a cutting-edge language can integrate across the stack. -**API Integration via Sanity:** Instead of building a backend from scratch, I used Sanity—a headless CMS—to deliver dynamic content. - -By merging Rust's backend strengths with Yew's frontend capabilities, this project showcases how Rust can be used as a full-stack solution for modern web applications. While time constraints prevented me from delving deeper into custom backend solutions with Actix, the setup with Sanity provided an efficient and reliable alternative. This project not only tested Rust’s capabilities but also pushed my understanding of how a cutting-edge language can integrate across the stack. +--- ## Brief History -You may use a bullet point list or subheadings to structure a timeline of your chosen topic's history: -- 2010: Rust is started by Mozilla to build a safer and faster browser engine (Servo). -- 2015: Rust is publicly released. -- 2015-2023: Rust gains traction in system programming and begins to make its mark in web development. -- Present: Rust is used by companies like Discord, Meta, Dropbox, and Figma. The rise of WebAssembly (Wasm) has enabled Rust to be used for both backend and frontend development, with frameworks like Yew showcasing its potential. +You may use a bullet point list or subheadings to structure a timeline of your chosen topic’s history: -## Main Features of Rust and Yew +- **2010:** Rust was initiated by Mozilla to build a safer and faster browser engine (Servo). +- **2015:** Rust is publicly released. +- **2015–2023:** Gains popularity in systems programming and starts making inroads in web development. +- **Present:** Used by well-known companies like Discord, Meta, Dropbox, and Figma. The rise of WebAssembly (Wasm) enables Rust to be deployed for both backend and frontend. Frameworks like **Yew** showcase Rust’s potential in the browser, allowing developers to write reactive and efficient web applications. -Describe the primary purpose of the tool that you have selected. Which problems does it solve? Is there something unique about this tool? How can it be useful to developers? +--- -You may use subheadings, tables or bullet points to structure your description: -- **Example Feature:** This feature does something for a specific reason. -- **Example Feature:** This feature does something for a specific reason. -- **Example Feature:** This feature does something for a specific reason. +## Main Features of Rust and Yew -Example feature table: +### Rust's Core Features -| Feature | Description | -| --- | --- | -| Memory Safety | Prevents memory errors without garbage collection using the ownership model.| -| Advanced Compiler|Acts as a code auditor, providing detailed error messages for safe coding. | -| Result Type| Ensures explicit error handling, avoiding unnoticed critical errors. | -| Ownership Model| Manages memory through strict ownership rules, ensuring safety and speed. | -| High Performance | Competes with C/C++ for speed while maintaining safety. | +| Feature | Description | +|----------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| **Memory Safety** | Prevents memory errors without garbage collection using the ownership model. | +| **Advanced Compiler**| Acts as a code auditor, providing detailed error messages for safer and more correct coding. | +| **Result Type** | Forces explicit error handling, preventing critical errors from going unnoticed. | +| **Ownership Model** | Manages memory through strict ownership rules, ensuring safety and performance. | +| **High Performance** | Competes with C/C++ in speed while preserving strict safety guarantees. | -**Unique Concepts in Rust** -- **PhantomData:** Allows developers to define state in a way that ensures safety and correctness. For instance, it can differentiate between unauthorized and authorized states to prevent accidental access to sensitive functions. -- **Result and Option Types:** Require explicit handling of success and failure cases, reducing runtime errors. +#### Unique Concepts in Rust +- **PhantomData**: Enables developers to encode type-state so the compiler prevents misuse of unauthorized states. For instance, you can differentiate between `Unauthorized` and `Authorized` states, ensuring only authenticated users can access certain functions. +- **Result and Option Types**: Require explicit handling of success and failure cases, reducing runtime surprises. +### Yew Framework -| Feature | Description | -| --- | --- | -| WebAssembly Support |Yew compiles to Wasm, offering better performance and lower resource usage. | -| Reactive UI | Enables modern, reactive user interfaces similar to React but in Rust. | -| Memory Safety | Inherits Rust’s safety and ownership model, reducing runtime errors.| -| Shared Codebase | Allows shared logic between frontend and backend.| -| Tailwind CSS Support | Simplifies styling by integrating with popular tools. | +| Feature | Description | +|--------------------------|---------------------------------------------------------------------------------------------------------------------------------| +| **WebAssembly Support** | Yew compiles to Wasm, offering better performance and lower resource usage compared to typical JavaScript frameworks. | +| **Reactive UI** | Enables modern, reactive interfaces similar to React, but with the added safety of Rust. | +| **Memory Safety** | Inherits Rust’s safety and ownership model, reducing runtime errors. | +| **Shared Codebase** | Allows for shared logic between frontend and backend when both are written in Rust. | +| **Tailwind CSS Support** | Integrates smoothly with popular styling frameworks like Tailwind, easing the styling process. | **Advantages** -- Faster and more resource-efficient than JavaScript-based frameworks. -- Strong type safety and better error handling. +- Faster and more resource-efficient than many JavaScript-based frameworks. +- Strong type safety and better error handling at compile time. - Seamless integration with Rust backend systems. **Challenges** -- Limited documentation and ecosystem compared to mature frontend frameworks. -- Requires knowledge of both Rust and WebAssembly, making onboarding steeper. +- Limited documentation and ecosystem maturity compared to JavaScript frameworks. +- Requires knowledge of both Rust and WebAssembly, steepening the learning curve. + +--- + +## Ownership Model in Rust +In many programming languages without a garbage collector (e.g., C and C++), developers must manually allocate and free memory. In languages like Go, JavaScript, or Java, you only need to declare a variable, and a garbage collector handles cleanup when memory is no longer needed. In Rust, the **ownership model** elegantly addresses memory management without relying on garbage collection. + +### Why the Ownership Model Matters + +Traditionally, manual memory management can lead to: +- **Memory Leaks**: Forgetting to free memory once it’s no longer needed. +- **Data Corruption**: Multiple parts of the program accidentally modifying the same memory simultaneously, leading to unpredictable behavior. + +Rust’s ownership model ensures each piece of data has a single “owner.” When that owner goes out of scope, Rust automatically frees the associated memory. This makes it impossible to accidentally reference data after it’s been freed, and it prevents data races by strictly controlling who can mutate data and when. + +### How Ownership Works in Practice + +When you declare a variable—say, a `BlogPost`—and pass it into a function, you transfer its ownership to that function. Once the function finishes and the variable goes out of scope, the memory is automatically freed. Rust also supports **mutable references**, allowing you to mutate data safely, but only under well-defined borrowing rules that prevent concurrent mutable access. + +Though these rules may initially seem restrictive, they ultimately reduce many common bugs to compile-time errors. Rust’s ownership model is a key reason why Rust programs are often both **fast** and **safe**. + +--- ## Market Comparison -When comparing Rust and Yew to other technologies, their unique advantages and limitations become evident. Rust offers unparalleled memory safety and performance, making it ideal for developers prioritizing reliability. However, its steep learning curve and strict ownership model may pose challenges for beginners. Yew, while fast and efficient due to WebAssembly, requires knowledge of Rust and has limited documentation, which can slow adoption. In contrast, technologies like JavaScript and React benefit from mature ecosystems but lack the inherent safety and performance of Rust and Yew. +When comparing Rust and Yew to more established technologies: + +- **Rust**: Offers unmatched memory safety and performance, making it ideal for developers seeking reliability. However, its **learning curve** can be significant, and its **ecosystem**—while fast-growing—is smaller compared to languages like JavaScript and Python. +- **Yew**: Provides efficient, reactive UIs via WebAssembly, benefiting from Rust’s safety guarantees. But it **requires Rust knowledge**, has fewer libraries, and less mature documentation compared to JavaScript frameworks like React or Vue. + +Technologies such as JavaScript and React enjoy robust ecosystems and widespread adoption but lack the inherent type safety and performance potential of Rust and Yew. + +--- ## Getting Started -If applicable, describe how to get started with your chosen tool. By providing examples, this can help to demystify a tool and make it more accessible to beginners. +### Rust -Rust +- **Ownership Model**: You must understand how ownership, borrowing, and lifetimes work to write idiomatic Rust. +- **Strict Typing**: While this leads to safer code, it can feel slower at first if you’re used to more permissive languages. +- **Growing Ecosystem**: Though Rust’s ecosystem is expanding, you may find fewer “off-the-shelf” solutions than in more mature languages. -Ownership Model: Demands a deep understanding of ownership, borrowing, and lifetimes. +### Yew -Strict Typing: Requires careful adherence to type rules, increasing development time initially. +- **Steep Learning Curve**: Familiarity with Rust and WebAssembly is needed. +- **Limited Documentation**: As an emerging framework, Yew’s documentation is improving but still limited compared to established frontend technologies. +- **Wasm Challenges**: Debugging in a browser can be more involved than typical JavaScript debugging. -Growing Ecosystem: While expanding, the ecosystem is not as extensive as other languages. +--- -Yew +## Key Takeaways: What This Project Tested -Steep Learning Curve: Requires knowledge of both Rust and WebAssembly. +1. **End-to-End Rust + Yew Application** + - Showcased how to build reactive UI components with Yew, manage app routing, and integrate Rust code on the frontend via WebAssembly. -Limited Documentation: Still early in development, making troubleshooting harder. +2. **Authentication & Authorization** + - Implemented a simple login system using `gloo_storage` to store user data, demonstrating how local storage can simulate session persistence. + - Showed **type-state** transitions with `PhantomData` to differentiate between unauthorized and authorized user states. -Wasm Challenges: Debugging and browser integration can be more complex than JavaScrit +3. **Routing and Navigation** + - Used Yew Router to seamlessly navigate between a Login page, Home page, and Article details. + - Ensured unauthorized users are automatically redirected to the Login page if they attempt to access protected content. +4. **Data Fetching & Serialization** + - Fetched blog posts and articles from a headless CMS (Sanity) using `gloo_net::http::Request`. + - Deserialized JSON responses into Rust structs with Serde (`Deserialize`), emphasizing type safety. +5. **Asynchronous Operations & Side Effects** + - Leveraged `wasm_bindgen_futures::spawn_local` and `use_effect_with` to fetch data without blocking the UI. + - Showed how to handle network errors and integrate logs via `gloo_console`. -## Conclusion +6. **Error Handling & Logging** + - Displayed user feedback for login failures or internal state issues. + - Relied on compile-time guarantees and the `Result` type to prevent hidden runtime errors. -Rust +7. **Styling & Tailwind Readiness** + - Used inline styles but structured the project to allow easy migration to **Tailwind CSS**. + - Demonstrated how Rust frameworks can incorporate modern styling approaches alongside Wasm. -Rust is a powerful and flexible language that delivers high performance and unparalleled safety. It is ideal for developers prioritizing reliability and correctness, especially in complex systems. +8. **Chrono for Date Handling** + - Showed basic date usage (`NaiveDate`), illustrating how Rust’s standard and third-party libraries can be combined in a web context. -Yew +Overall, these features illustrate how Rust’s strict safety guarantees and Yew’s Wasm-powered frontend can be integrated to create a secure, high-performance, and type-safe web application. -Yew demonstrates that Rust can be a viable alternative for frontend development. While it is still in its early stages, it provides a promising path for full-stack development with Rust, offering better safety and performance than many current technologies. +--- -Both Rust and Yew require significant time and effort to master, but the results are applications that are faster, safer, and more robust than most alternatives. +## Conclusion -## References +### Rust + +Rust is both powerful and flexible, offering high performance alongside guarantees of memory and thread safety. It’s ideal for developers prioritizing reliability and correctness, especially in large, complex systems. While there is an initial learning hurdle due to the ownership model, the long-term payoff is safer, more maintainable code. + +### Yew + +Yew demonstrates that Rust can be a viable frontend solution, compiling to WebAssembly and providing reactive UIs similar to JavaScript frameworks. Though it’s in an earlier stage of development with limited documentation, Yew holds promise as a path to a unified Rust-based stack—from system-level code all the way to the browser. -- [Rust](https://www.rust-lang.org/) -- [Yew](https://yew.rs/) -- [Webassembly](https://webassembly.org/) +Both Rust and Yew demand a substantial investment of time and effort. However, the result is applications that are typically faster, safer, and more robust than those built with many other language and framework combinations. +--- + +## References +- [Rust Official Website](https://www.rust-lang.org/) +- [Yew Framework](https://yew.rs/) +- [WebAssembly](https://webassembly.org/) +- [Sanity](https://www.sanity.io/) From 97c8b8a16197d90217bb346ce10eace1c9e0a8c8 Mon Sep 17 00:00:00 2001 From: EPetrineLynghaug <136695793+EPetrineLynghaug@users.noreply.github.com> Date: Sun, 19 Jan 2025 19:16:45 +0100 Subject: [PATCH 6/8] . --- src/content/docs/rust-and-yew/rust-and-yew.md | 220 ++++++++---------- 1 file changed, 103 insertions(+), 117 deletions(-) diff --git a/src/content/docs/rust-and-yew/rust-and-yew.md b/src/content/docs/rust-and-yew/rust-and-yew.md index 548479c4d..f00514e47 100644 --- a/src/content/docs/rust-and-yew/rust-and-yew.md +++ b/src/content/docs/rust-and-yew/rust-and-yew.md @@ -1,168 +1,148 @@ --- title: Case Study Rust and Yew Framework -author: Elisabeth Petrine Lynghaug -tags: example, case study, platform +author: E. Petrine Lnghaug +tags: example, case study, Rust, Framework. --- ## Introduction -Working with Rust has been both a challenge and a joy. Rust is a modern programming language renowned for its security, high performance, and memory safety—achieved without a garbage collector. Originally developed by Mozilla to build a faster and safer browser engine (Servo), Rust stands out thanks to its **ownership model**, which automatically manages memory and prevents common errors like data races and memory leaks. +Working with Rust has been both a challenge and a joy. Rust is a modern programming language renowned for its security, high performance, and memory safety—achieved without relying on a garbage collector. Originally developed by Mozilla to build a faster and safer browser engine (Servo), Rust stands out due to its **ownership model**, which automatically manages memory and prevents common errors like data races and memory leaks. -The goal of this project was to build a login application that illustrates how Rust can be used in a full-stack environment: +For this case study, I built a **login application** that illustrates how Rust can be used as an end-to-end solution: -- **Strong Typing and Error Handling:** Showcasing how Rust’s type system prevents errors and guarantees safety. -- **Frontend Exploration with Yew:** Leveraging Yew, a Rust-based framework compiled to WebAssembly, to write frontend logic in Rust. -- **API Integration via Sanity:** Instead of creating a custom backend (e.g., using Actix), Sanity (a headless CMS) was used to deliver dynamic content. +- **Strong Typing and Error Handling:** Rust’s type system catches mistakes at compile time, guaranteeing safer code. +- **Frontend Exploration with Yew:** A Rust-based frontend framework compiled to WebAssembly, enabling reactive UI development in Rust. +- **API Integration via Sanity:** Leveraging a headless CMS rather than implementing a custom backend for data storage. -By combining Rust’s backend strengths with Yew’s frontend capabilities, this project highlights how Rust can serve as an end-to-end tool for modern application development. Although time constraints meant I did not implement a custom backend in Rust, using Sanity provided a reliable and efficient alternative. Throughout this project, I challenged my own understanding of Rust and discovered how a cutting-edge language can integrate across the stack. - ---- +By combining Rust’s backend strengths with Yew’s frontend capabilities, this project tests the feasibility of a unified Rust stack. Although I did not create a custom backend (e.g., via Actix) due to time constraints, using Sanity proved a reliable and efficient alternative. The experience not only pushed my understanding of Rust’s capabilities but also demonstrated how a modern language can integrate seamlessly across the stack. ## Brief History -You may use a bullet point list or subheadings to structure a timeline of your chosen topic’s history: - -- **2010:** Rust was initiated by Mozilla to build a safer and faster browser engine (Servo). +- **2010:** Rust is started by Mozilla to build a safer and faster browser engine (Servo). - **2015:** Rust is publicly released. -- **2015–2023:** Gains popularity in systems programming and starts making inroads in web development. -- **Present:** Used by well-known companies like Discord, Meta, Dropbox, and Figma. The rise of WebAssembly (Wasm) enables Rust to be deployed for both backend and frontend. Frameworks like **Yew** showcase Rust’s potential in the browser, allowing developers to write reactive and efficient web applications. - ---- +- **2015–2023:** Gains popularity in systems programming and makes inroads into web development. +- **Present:** Rust is used by companies such as Discord, Meta, Dropbox, and Figma. The rise of WebAssembly (Wasm) has enabled Rust to run in both backend and frontend environments. Frameworks like **Yew** showcase Rust’s potential in the browser, allowing developers to write reactive and efficient web applications. -## Main Features of Rust and Yew +## Main Features -### Rust's Core Features +Rust and Yew each bring unique strengths to modern web development. -| Feature | Description | -|----------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| **Memory Safety** | Prevents memory errors without garbage collection using the ownership model. | -| **Advanced Compiler**| Acts as a code auditor, providing detailed error messages for safer and more correct coding. | -| **Result Type** | Forces explicit error handling, preventing critical errors from going unnoticed. | -| **Ownership Model** | Manages memory through strict ownership rules, ensuring safety and performance. | -| **High Performance** | Competes with C/C++ in speed while preserving strict safety guarantees. | +### Rust’s Core Features -#### Unique Concepts in Rust - -- **PhantomData**: Enables developers to encode type-state so the compiler prevents misuse of unauthorized states. For instance, you can differentiate between `Unauthorized` and `Authorized` states, ensuring only authenticated users can access certain functions. -- **Result and Option Types**: Require explicit handling of success and failure cases, reducing runtime surprises. - -### Yew Framework - -| Feature | Description | -|--------------------------|---------------------------------------------------------------------------------------------------------------------------------| -| **WebAssembly Support** | Yew compiles to Wasm, offering better performance and lower resource usage compared to typical JavaScript frameworks. | -| **Reactive UI** | Enables modern, reactive interfaces similar to React, but with the added safety of Rust. | -| **Memory Safety** | Inherits Rust’s safety and ownership model, reducing runtime errors. | -| **Shared Codebase** | Allows for shared logic between frontend and backend when both are written in Rust. | -| **Tailwind CSS Support** | Integrates smoothly with popular styling frameworks like Tailwind, easing the styling process. | +Rust solves significant problems often encountered in systems programming: -**Advantages** -- Faster and more resource-efficient than many JavaScript-based frameworks. -- Strong type safety and better error handling at compile time. -- Seamless integration with Rust backend systems. +- **Memory Safety without Garbage Collection** +- **Strict Ownership Model** (avoids data races and use-after-free errors) +- **Advanced Compiler** (detailed error messages, strict borrow checker) +- **Result & Option Types** (forcing explicit error handling) +- **High Performance** (comparable to C/C++) -**Challenges** -- Limited documentation and ecosystem maturity compared to JavaScript frameworks. -- Requires knowledge of both Rust and WebAssembly, steepening the learning curve. +#### Example Feature Table for Rust ---- +| Feature | Description | +|-------------------|---------------------------------------------------------------------------------------------------------------| +| Memory Safety | Prevents memory errors by enforcing strict ownership rules at compile time. | +| Advanced Compiler | Acts as a code auditor, providing detailed error messages for safer, more correct coding. | +| Result Type | Forces explicit handling of success/failure paths, minimizing hidden runtime errors. | +| Ownership Model | Manages memory without GC, eliminating entire classes of concurrency issues. | +| High Performance | Rust can match C/C++ in speed, making it suitable for performance-critical tasks. | -## Ownership Model in Rust +### Yew Framework -In many programming languages without a garbage collector (e.g., C and C++), developers must manually allocate and free memory. In languages like Go, JavaScript, or Java, you only need to declare a variable, and a garbage collector handles cleanup when memory is no longer needed. In Rust, the **ownership model** elegantly addresses memory management without relying on garbage collection. +Yew is a frontend framework for building web apps in Rust, compiled to WebAssembly. -### Why the Ownership Model Matters +- **WebAssembly Support:** Offers faster load times and execution compared to JavaScript in some scenarios. +- **Reactive UI:** Similar in style to React, but with Rust’s safety guarantees. +- **Memory Safety:** Inherits Rust’s strong compile-time checks. +- **Shared Codebase:** Allows developers to share logic between backend and frontend. +- **Tailwind CSS Support:** Easily integrates with popular CSS frameworks. -Traditionally, manual memory management can lead to: -- **Memory Leaks**: Forgetting to free memory once it’s no longer needed. -- **Data Corruption**: Multiple parts of the program accidentally modifying the same memory simultaneously, leading to unpredictable behavior. +#### Example Feature Table for Yew -Rust’s ownership model ensures each piece of data has a single “owner.” When that owner goes out of scope, Rust automatically frees the associated memory. This makes it impossible to accidentally reference data after it’s been freed, and it prevents data races by strictly controlling who can mutate data and when. +| Feature | Description | +|--------------------------|---------------------------------------------------------------------------------------------------------------------------------| +| WebAssembly Support | Compiles to Wasm, offering better performance and smaller resource usage. | +| Reactive UI | Enables reactive UIs, akin to React, but leveraging Rust’s type system for added safety. | +| Memory Safety | Inherits Rust’s ownership model, reducing runtime errors and crashes. | +| Shared Codebase | Lets you share Rust code across server and client. | +| Tailwind CSS Support | Integrates smoothly with utility-first styling libraries like Tailwind. | -### How Ownership Works in Practice +### Ownership Model in Rust -When you declare a variable—say, a `BlogPost`—and pass it into a function, you transfer its ownership to that function. Once the function finishes and the variable goes out of scope, the memory is automatically freed. Rust also supports **mutable references**, allowing you to mutate data safely, but only under well-defined borrowing rules that prevent concurrent mutable access. +Many languages rely on manual memory management (C, C++) or garbage collection (Go, Java, JavaScript). Rust takes a different approach with its **ownership model**: -Though these rules may initially seem restrictive, they ultimately reduce many common bugs to compile-time errors. Rust’s ownership model is a key reason why Rust programs are often both **fast** and **safe**. +- **Why It Matters:** + - Avoids memory leaks by having a single “owner” for each piece of data. + - Prevents data corruption via strict rules that ensure only one mutable reference at a time. +- **How It Works:** + - When a variable (e.g., `BlogPost`) goes out of scope, Rust automatically frees it. + - Rust’s “borrow checker” enforces correct reference usage at compile time. ---- +This model may feel restrictive at first, but it practically eliminates entire classes of bugs, making Rust applications both **fast** and **safe**. ## Market Comparison -When comparing Rust and Yew to more established technologies: +### Rust vs. Other Languages -- **Rust**: Offers unmatched memory safety and performance, making it ideal for developers seeking reliability. However, its **learning curve** can be significant, and its **ecosystem**—while fast-growing—is smaller compared to languages like JavaScript and Python. -- **Yew**: Provides efficient, reactive UIs via WebAssembly, benefiting from Rust’s safety guarantees. But it **requires Rust knowledge**, has fewer libraries, and less mature documentation compared to JavaScript frameworks like React or Vue. +- **Rust**: Excellent memory safety, high performance, steep learning curve, smaller (but growing) ecosystem. +- **C++**: Faster for some tasks, but more prone to memory errors without careful manual management. +- **Go**: Garbage-collected, simpler concurrency model, but lacks Rust’s fine-grained control and zero-cost abstractions. +- **JavaScript**: Ubiquitous for frontend, huge ecosystem, but can’t match Rust’s performance or type safety. -Technologies such as JavaScript and React enjoy robust ecosystems and widespread adoption but lack the inherent type safety and performance potential of Rust and Yew. +### Yew vs. Traditional JavaScript Frameworks ---- +- **Yew**: + - Pros: Compiles to WebAssembly, strong typing, potential for high performance. + - Cons: Smaller community, less documentation, requires Rust/WebAssembly knowledge. + +- **React / Vue / Angular**: + - Pros: Very large ecosystems, extensive documentation, established patterns. + - Cons: Less inherent safety, must handle typical JavaScript pitfalls like runtime type errors. ## Getting Started ### Rust -- **Ownership Model**: You must understand how ownership, borrowing, and lifetimes work to write idiomatic Rust. -- **Strict Typing**: While this leads to safer code, it can feel slower at first if you’re used to more permissive languages. -- **Growing Ecosystem**: Though Rust’s ecosystem is expanding, you may find fewer “off-the-shelf” solutions than in more mature languages. +1. **Install Rust**: + - Download from [rust-lang.org](https://www.rust-lang.org/tools/install). + - Use `rustup` to manage versions. +2. **Learn the Ownership Model**: + - Understand how borrowing, references, and lifetimes work. +3. **Explore Crates**: + - Utilize community-maintained libraries from [crates.io](https://crates.io). ### Yew -- **Steep Learning Curve**: Familiarity with Rust and WebAssembly is needed. -- **Limited Documentation**: As an emerging framework, Yew’s documentation is improving but still limited compared to established frontend technologies. -- **Wasm Challenges**: Debugging in a browser can be more involved than typical JavaScript debugging. - ---- - -## Key Takeaways: What This Project Tested - -1. **End-to-End Rust + Yew Application** - - Showcased how to build reactive UI components with Yew, manage app routing, and integrate Rust code on the frontend via WebAssembly. - -2. **Authentication & Authorization** - - Implemented a simple login system using `gloo_storage` to store user data, demonstrating how local storage can simulate session persistence. - - Showed **type-state** transitions with `PhantomData` to differentiate between unauthorized and authorized user states. - -3. **Routing and Navigation** - - Used Yew Router to seamlessly navigate between a Login page, Home page, and Article details. - - Ensured unauthorized users are automatically redirected to the Login page if they attempt to access protected content. - -4. **Data Fetching & Serialization** - - Fetched blog posts and articles from a headless CMS (Sanity) using `gloo_net::http::Request`. - - Deserialized JSON responses into Rust structs with Serde (`Deserialize`), emphasizing type safety. - -5. **Asynchronous Operations & Side Effects** - - Leveraged `wasm_bindgen_futures::spawn_local` and `use_effect_with` to fetch data without blocking the UI. - - Showed how to handle network errors and integrate logs via `gloo_console`. - -6. **Error Handling & Logging** - - Displayed user feedback for login failures or internal state issues. - - Relied on compile-time guarantees and the `Result` type to prevent hidden runtime errors. - -7. **Styling & Tailwind Readiness** - - Used inline styles but structured the project to allow easy migration to **Tailwind CSS**. - - Demonstrated how Rust frameworks can incorporate modern styling approaches alongside Wasm. - -8. **Chrono for Date Handling** - - Showed basic date usage (`NaiveDate`), illustrating how Rust’s standard and third-party libraries can be combined in a web context. - -Overall, these features illustrate how Rust’s strict safety guarantees and Yew’s Wasm-powered frontend can be integrated to create a secure, high-performance, and type-safe web application. - ---- +1. **Setup a New Project**: + - Use `cargo new` to create a Rust project. + - Add Yew and WebAssembly tools in `Cargo.toml`: + ```toml + [dependencies] + yew = "0.20" + wasm-bindgen = "0.2" + ``` +2. **Install Trunk or wasm-pack**: + - Trunk automates building and serving Yew apps. + - `cargo install trunk` +3. **Compile to WebAssembly**: + - Run `trunk serve` or `wasm-pack build --target web`. +4. **Integrate Tailwind**: + - Configure Tailwind’s `postcss.config.js` or `tailwind.config.js`. + - Replace inline styles with Tailwind classes. ## Conclusion -### Rust - -Rust is both powerful and flexible, offering high performance alongside guarantees of memory and thread safety. It’s ideal for developers prioritizing reliability and correctness, especially in large, complex systems. While there is an initial learning hurdle due to the ownership model, the long-term payoff is safer, more maintainable code. - -### Yew - -Yew demonstrates that Rust can be a viable frontend solution, compiling to WebAssembly and providing reactive UIs similar to JavaScript frameworks. Though it’s in an earlier stage of development with limited documentation, Yew holds promise as a path to a unified Rust-based stack—from system-level code all the way to the browser. +Rust excels at performance-critical, safety-centric development, and Yew extends these benefits to the frontend by leveraging WebAssembly. While both come with a steep learning curve and smaller ecosystems compared to more established languages and frameworks, the payoff is in robust, maintainable, and performant applications. -Both Rust and Yew demand a substantial investment of time and effort. However, the result is applications that are typically faster, safer, and more robust than those built with many other language and framework combinations. +- **Advantages**: + - Compile-time guarantees reduce runtime errors. + - Memory safety without a garbage collector. + - Potential for a truly full-stack Rust solution. +- **Disadvantages**: + - Less documentation and fewer ready-made libraries than mainstream frontend frameworks. + - Rust’s strict ownership model can be daunting for newcomers. ---- +Despite these hurdles, the future for Rust and Yew looks promising as WebAssembly adoption continues to grow, attracting both low-level systems developers and high-level application creators. ## References @@ -170,3 +150,9 @@ Both Rust and Yew demand a substantial investment of time and effort. However, t - [Yew Framework](https://yew.rs/) - [WebAssembly](https://webassembly.org/) - [Sanity](https://www.sanity.io/) + +## Additional Resources + +- [Rust Book](https://doc.rust-lang.org/book/) +- [Examples of WebAssembly + Yew](https://github.com/yewstack/yew/tree/master/examples) +- [Tailwind CSS Documentation](https://tailwindcss.com/docs) From 290c938ef945e79bf4d27def6ea24ed99b2acf8d Mon Sep 17 00:00:00 2001 From: EPetrineLynghaug <136695793+EPetrineLynghaug@users.noreply.github.com> Date: Thu, 30 Jan 2025 21:08:28 +0100 Subject: [PATCH 7/8] Moved rust-and-yew.md to correct directory --- src/content/docs/{rust-and-yew => rust}/rust-and-yew.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename src/content/docs/{rust-and-yew => rust}/rust-and-yew.md (100%) diff --git a/src/content/docs/rust-and-yew/rust-and-yew.md b/src/content/docs/rust/rust-and-yew.md similarity index 100% rename from src/content/docs/rust-and-yew/rust-and-yew.md rename to src/content/docs/rust/rust-and-yew.md From 30257976d8f571da1aa8562aa05ba0371118e33f Mon Sep 17 00:00:00 2001 From: EPetrineLynghaug <136695793+EPetrineLynghaug@users.noreply.github.com> Date: Thu, 30 Jan 2025 21:12:33 +0100 Subject: [PATCH 8/8] . --- src/content/docs/rust/rust-and-yew.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/content/docs/rust/rust-and-yew.md b/src/content/docs/rust/rust-and-yew.md index f00514e47..8695e8f05 100644 --- a/src/content/docs/rust/rust-and-yew.md +++ b/src/content/docs/rust/rust-and-yew.md @@ -1,7 +1,7 @@ --- title: Case Study Rust and Yew Framework author: E. Petrine Lnghaug -tags: example, case study, Rust, Framework. +tags: case study, Rust, Framework. --- ## Introduction