Ultimate Guide to GUI Development Frameworks in Programming Languages (Open-Source Libraries)

Introduction to GUI Development in Popular Programming Languages

Graphical User Interface (GUI) development is essential for creating interactive and user-friendly applications across various platforms. Whether you’re developing desktop, mobile, or web applications, the choice of a programming language and its corresponding GUI framework can significantly impact your project’s success. This article provides a detailed overview of 80 GUI frameworks across multiple programming languages, highlighting their key features and providing official links for further exploration.

A Detailed Guide to Cross-Platform GUI Frameworks in Popular Programming Languages

1. Python

Python is widely known for its simplicity and readability, making it a popular choice for beginners and experienced developers alike. Here are some of the most popular GUI frameworks in Python:

GUI FrameworkKey FeaturesOfficial Link
TkinterBuilt-in, easy to use, lightweight, cross-platformTkinter
PyQtComprehensive, cross-platform, supports Qt Designer, commercial license availablePyQt
KivyOpen-source, cross-platform, multitouch, GPU acceleratedKivy
wxPythonNative look and feel, cross-platform, supports older versions of PythonwxPython
PyGTKGNOME-based, cross-platform, supports native Linux themesPyGTK
PySideOfficial Qt for Python, LGPL licensed, powerful, cross-platformPySide
PySimpleGUISimple to use, wraps around other GUI frameworks, cross-platformPySimpleGUI
Dear PyGuiImmediate Mode GUI, GPU accelerated, cross-platformDear PyGui
PygameSpecifically for game development, easy to use, cross-platformPygame
TogaPart of the BeeWare project, native GUI toolkit, cross-platformToga

2. C++

C++ is a powerful programming language commonly used for system/software development, game development, and performance-critical applications. Below are some of the most popular C++ GUI frameworks:

GUI FrameworkKey FeaturesOfficial Link
QtExtensive, cross-platform, commercial support, rich UI toolsQt
wxWidgetsCross-platform, native look and feel, free and open-sourcewxWidgets
GTK+Open-source, used by GNOME, cross-platformGTK+
FLTKLightweight, cross-platform, minimal dependenciesFLTK
ImGuiImmediate Mode GUI, optimized for performance, lightweight, cross-platformImGui
JUCEDesigned for audio applications, cross-platform, modern UIJUCE
CEGUICustomizable, cross-platform, designed for gamesCEGUI
NanaModern C++11 style, cross-platform, lightweightNana
Ultimate++Modern C++ GUI framework, rich features, cross-platformUltimate++
AntTweakBarLightweight, for small GUI applications, easy integrationAntTweakBar

3. Java

Java is a versatile and widely-used programming language, especially known for its portability across platforms. Here are some popular Java GUI frameworks:

GUI FrameworkKey FeaturesOfficial Link
SwingPart of Java Standard Library, lightweight, cross-platformSwing
JavaFXRich set of UI controls, 3D graphics, web view, cross-platformJavaFX
SWTNative look and feel, developed by IBM, cross-platformSWT
AWTBasic UI components, part of Java Standard Library, lightweightAWT
JFoenixMaterial Design components for JavaFXJFoenix
VaadinWeb framework, Java-based, cross-platformVaadin
Apache PivotOpen-source, rich set of components, cross-platformApache Pivot
ThinletLightweight, XML-based, designed for small GUIsThinlet
LanternaText-based UI, terminal applications, cross-platformLanterna
JFreeChartCharting library, extensive, easy to useJFreeChart

4. C#

C# is a popular language for Windows applications, particularly within the .NET ecosystem. Below are some widely-used C# GUI frameworks:

GUI FrameworkKey FeaturesOfficial Link
Windows FormsEasy to use, part of .NET, Windows-onlyWindows Forms
WPFAdvanced graphics, data binding, part of .NET, Windows-onlyWPF
AvaloniaCross-platform, XAML-based, modern UI frameworkAvalonia
Uno PlatformCross-platform, single codebase, based on UWPUno Platform
Eto.FormsCross-platform, shared code, multiple backendsEto.Forms
MAUICross-platform, next-gen Xamarin.Forms, built on .NETMAUI
Xamarin.FormsCross-platform, mobile-first, part of XamarinXamarin.Forms
CefSharpEmbedded browser, based on Chromium, supports WPF and Windows FormsCefSharp
WinUIModern native UI, Windows 10+, scalableWinUI
OpenTKAdvanced graphics, game development, cross-platformOpenTK

5. JavaScript

JavaScript is the language of the web, and many frameworks are available for building web-based GUIs and even desktop applications through hybrid frameworks:

GUI FrameworkKey FeaturesOfficial Link
ElectronCross-platform, web-based, uses Chromium and Node.jsElectron
NW.jsCross-platform, uses Node.js and WebKit, deep Node.js integrationNW.js
React NativeCross-platform, mobile-first, declarative UI, backed by FacebookReact Native
Vue.js with ElectronLightweight, reactive components, combined with Electron for desktop appsVue.js
Angular ElectronFramework for building Electron apps with AngularAngular Electron
NodeGUINative desktop apps with JavaScript, uses QtNodeGUI
BootstrapHTML/CSS/JS framework, responsive design, cross-platformBootstrap
FoundationResponsive front-end framework, mobile-first, cross-platformFoundation
QuasarHigh-performance, cross-platform, Vue-basedQuasar
Ext JSRich UI components, enterprise-level, responsiveExt JS

6. Swift

Swift is Apple’s language for developing macOS, iOS, watchOS, and tvOS applications. Below are some key GUI frameworks in Swift:

GUI FrameworkKey FeaturesOfficial Link
SwiftUIDeclarative syntax, seamless integration with Apple ecosystems, modern and responsive UI frameworkSwiftUI
CocoaNative macOS and iOS framework, extensive integration with Apple servicesCocoa
AppKitFoundation of Cocoa for macOS, used for building native macOS appsAppKit
UIKitUI framework for iOS, tvOS, watchOS, part of Apple’s Cocoa Touch frameworkUIKit
VaporServer-side Swift framework, good for web applications with SwiftVapor
PerfectServer-side Swift framework, flexible routing, web-based GUIsPerfect
KituraLightweight, IBM-supported, cross-platform web frameworkKitura
SwiftWebUIBrings SwiftUI’s declarative syntax to the webSwiftWebUI
TonicTiny, reactive UI library for SwiftUI on iOS/macOSTonic
SwiftPlotData visualization and plotting for SwiftSwiftPlot

7. Dart

Dart is a language optimized for building fast, cross-platform applications. It’s best known for its use in Flutter, but there are other GUI frameworks available as well:

GUI FrameworkKey FeaturesOfficial Link
FlutterCross-platform, mobile-first, modern UI, built on DartFlutter
AngularDartWeb framework, built on Dart, Google-supportedAngularDart
OverReactReact-like framework for building UIs in DartOverReact
HummingbirdEarly-stage, experimental project to run Flutter on the webHummingbird
StageXL2D game framework, focused on web, based on DartStageXL
Druid (Dart)Lightweight, cross-platform, inspired by FlutterDruid (Dart)
ReactiveX (RxDart)Library for composing asynchronous and event-based programs using Dart and reactive programmingReactiveX
FlintSmall UI library for Dart, component-basedFlint
DashWeb-based framework, designed for building analytical applications in DartDash
AqueductWeb server framework, ORM, based on DartAqueduct

8. Ruby

Ruby is a dynamic, reflective, object-oriented programming language known for its simplicity and productivity. Below are some GUI frameworks used in Ruby:

GUI FrameworkKey FeaturesOfficial Link
Ruby GTKGNOME-based, cross-platform, Ruby bindings for GTKRuby GTK
ShoesSimple and intuitive, ideal for beginners, cross-platformShoes
FXRubyRuby bindings for FOX Toolkit, native look and feel, cross-platformFXRuby
Tk (Ruby bindings)Simple, built-in with Ruby, cross-platformRuby Tk
QtRubyRuby bindings for Qt, powerful and flexible, cross-platformQtRuby
GosuSimple 2D game development, fast and easy to useGosu
GlimmerDSL for writing GUI apps, Ruby bindings for SWT, cross-platformGlimmer
RuGUILightweight, Ruby GUI toolkit, easy to useRuGUI
Green ShoesUpdated version of Shoes, better documentation, cross-platformGreen Shoes
VedeuTerminal-based, text user interfaces, cross-platformVedeu

9. Go

Go, or Golang, is a statically typed, compiled language known for its simplicity and performance. Below are some GUI frameworks available for Go:

GUI FrameworkKey FeaturesOfficial Link
FyneCross-platform, mobile and desktop, simple APIFyne
GioImmediate Mode GUI, based on Go, lightweight and fastGio
GoQtGo bindings for Qt, extensive features, cross-platformGoQt
WalkWindows GUI toolkit for Go, easy to use, native Windows look and feelWalk
LorcaSimple API, lightweight, uses HTML/CSS/JS for UI, cross-platformLorca
EbitenSimple game library for Go, 2D graphics, cross-platformEbiten
GopherJSCompiler, translates Go code to JavaScript, useful for web-based GUIsGopherJS
QtGoGo bindings for Qt, supports modern Qt features, cross-platformQtGo
gotk3GTK3 bindings for Go, native look and feel, cross-platformgotk3
WailsLightweight framework for creating web-based GUIs for desktop applications in GoWails

10. Rust

Rust is known for its memory safety and performance, making it an excellent choice for systems programming. Here are some GUI frameworks available for Rust:

GUI FrameworkKey FeaturesOfficial Link
DruidCross-platform, data-oriented, Rust-first GUI frameworkDruid
GTK-rsRust bindings for GTK, cross-platform, mature and stableGTK-rs
IcedCross-platform, reactive UI framework, inspired by ElmIced
ConrodImmediate Mode GUI, cross-platform, easy to integrateConrod
AzulDesktop GUI framework, focuses on performance, uses WebRenderAzul
SlintUI toolkit for Rust, modern declarative UI designSlint
TauriLightweight, desktop applications with web technologies, security-focusedTauri
OrbTkLightweight, modular, cross-platformOrbTk
ServoModern web engine written in Rust, great for web-based GUIsServo
SmithayWayland compositor framework for building Rust-based GUIsSmithay

11. C

C is a powerful language that is widely used in systems programming, embedded systems, and applications requiring high performance. Below are some popular GUI frameworks available in C:

GUI FrameworkKey FeaturesOfficial Link
GTK+Open-source, used by GNOME, cross-platformGTK+
NuklearImmediate Mode GUI, minimal dependencies, cross-platformNuklear
FLTKLightweight, cross-platform, C-firstFLTK
CursesText-based UI, simple and lightweight, cross-platformCurses
XFormsLightweight, open-source, used for X11 on UNIX, cross-platformXForms
WinAPINative Windows GUI, extensive, high performanceWinAPI
AllegroGame programming library, supports basic GUI functionalityAllegro
SDLLow-level access to audio, keyboard, mouse, 3D hardware via OpenGLSDL
EFL (Enlightenment Foundation Libraries)Lightweight, performance-oriented, used by the Enlightenment desktop environmentEFL
XlibLow-level C language interface to the X Window System protocolXlib

12. Haskell

Haskell is a statically typed, purely functional programming language. Below are some GUI frameworks available for Haskell:

GUI FrameworkKey FeaturesOfficial Link
Gtk2HsHaskell bindings for GTK, cross-platformGtk2Hs
wxHaskellHaskell bindings for wxWidgets, native look and feelwxHaskell
Threepenny-GUILightweight, functional, uses web browser as GUIThreepenny-GUI
ReflexFunctional Reactive Programming (FRP) library for GUIs, web-basedReflex
BrickTerminal-based, declarative, cross-platformBrick
GlossEasy to use, focuses on 2D graphics, cross-platformGloss
GI-GTKModern, based on GObject Introspection, cross-platformGI-GTK
VtyTerminal user interfaces, pure HaskellVty
fltkhsHaskell bindings for FLTK, lightweight, cross-platformfltkhs
HsQMLHaskell binding to the Qt Quick GUI library, cross-platformHsQML

13. Lua

Lua is a lightweight, high-level scripting language often used for embedded applications and games. Here are some GUI frameworks available for Lua:

GUI FrameworkKey FeaturesOfficial Link
Love2DSimple API, easy to learn, 2D-focused, game developmentLove2D
IUPPortable, easy to use, cross-platform GUI toolkitIUP
LÖVRVR-focused, easy to use, lightweightLÖVR
MoonshineLightweight, 2D-focused, game developmentMoonshine
Nuklear (via Lua bindings)Immediate Mode GUI, minimal dependencies, cross-platformNuklear-Lua
Torch7Scientific computing framework, neural networks, cross-platformTorch7
FengariLua interpreter, runs in the browser, JavaScript interopFengari
DefoldCross-platform game engine with Lua scripting, lightweightDefold
Pico-8Fantasy console for making, sharing, and playing tiny games and other computer programsPico-8
Corona SDKMobile app development framework with Lua, easy to useCorona SDK

14. PHP

PHP is widely used for web development, and it has some frameworks that allow for the creation of web-based GUI applications:

GUI FrameworkKey FeaturesOfficial Link
LaravelElegant syntax, MVC architecture, extensive ecosystemLaravel
SymfonyReusable PHP components, modular, enterprise-levelSymfony
CodeIgniterLightweight, simple to use, small footprintCodeIgniter
Yii FrameworkHigh-performance, component-based PHP frameworkYii Framework
PhalconHigh-performance, low-level, written in C, very fastPhalcon
Zend FrameworkEnterprise-grade, object-oriented, comprehensive set of featuresZend Framework
CakePHPRapid development framework, scaffolding, easy to useCakePHP
Slim FrameworkMicro framework, simple yet powerful, very flexibleSlim Framework
LaminasEnterprise-level, continuation of Zend Framework, modularLaminas
FuelPHPFull-featured PHP framework, modular, security-focusedFuelPHP

15. Perl

Perl, known for its strengths in text processing and scripting, also has GUI frameworks for building desktop and web applications:

GUI FrameworkKey FeaturesOfficial Link
Perl/TkPerl bindings for Tk, easy to use, cross-platformPerl/Tk
Gtk2-PerlPerl bindings for GTK, cross-platform, native look and feelGtk2-Perl
PrimaGUI toolkit for Perl, custom widgets, cross-platformPrima
wxPerlPerl bindings for wxWidgets, cross-platform, native look and feelwxPerl
CamelBonesCocoa framework for MacOS, specifically for PerlCamelBones
MojoReal-time web framework, non-blocking, event-drivenMojolicious
MasonWeb application framework, integrates with ApacheMason
DancerLightweight web application framework, simple DSLDancer
CatalystMVC web framework, highly flexible and modularCatalyst
PadreIDE for Perl, includes Perl/Tk, cross-platformPadre
GUI development frameworks in popular programming languages

Conclusion

This table provides a comprehensive overview of 80 GUI frameworks across multiple programming languages, offering developers a broad range of options for creating user interfaces. Whether you’re a beginner looking for an easy-to-learn framework or an experienced developer seeking a powerful tool for complex applications, this guide should help you find the right framework for your needs.

By exploring the official links provided, you can delve deeper into each framework’s features and capabilities, ensuring you choose the best option for your next project.


Tags: GUI development, programming languages, cross-platform frameworks, desktop applications, open-source libraries

Rust Programming: Build a Temperature Converter with Functions and Loops

Rust Programming

Introduction

Rust programming is known for its performance, safety, and modern features that make it an increasingly popular choice for systems programming. If you’re new to Rust, one of the best ways to get acquainted with its syntax and functionalities is by building small, practical applications. In this tutorial, we’ll create a simple Rust program that converts temperatures between Celsius and Fahrenheit. This project will help you understand fundamental Rust concepts such as functions, loops, user input, and type conversions.

This guide is perfect for beginners who want to dive into Rust with a hands-on project. Along the way, we’ll explain the code in detail so you can learn the language step by step.

Prerequisites

Before starting, make sure you have Rust installed on your machine. You can install Rust using rustup, which is the recommended way to install Rust. To learn more about Rust, visit the official Rust website. If you haven’t set up your Rust environment yet, check out the Cargo documentation for details on how to get started.

The Program: Temperature Converter

Our program will allow users to choose between converting from Celsius to Fahrenheit or from Fahrenheit to Celsius. The program will continue running until the user decides to quit. Here’s the complete code, which we’ll break down in the following sections.

The Complete Code

use std::io;

fn main() {
    println!("Hello, Rust Chapter 3!");

    loop {
        let what_to_do = get_user_input("Enter 1 to convert from Celsius to Fahrenheit, or 2 to convert from Fahrenheit to Celsius: ");

        if what_to_do == 1.0 {
            let celsius = get_user_input("Enter the temperature in Celsius: ");
            let fahrenheit = convert_to_fahrenheit(celsius);
            println!("{} Celsius is {} Fahrenheit.", celsius, fahrenheit);
        } else if what_to_do == 2.0 {
            let fahrenheit = get_user_input("Enter the temperature in Fahrenheit: ");
            let celsius = convert_to_celsius(fahrenheit);
            println!("{} Fahrenheit is {} Celsius.", fahrenheit, celsius);
        } else {
            println!("Invalid input. Please enter 1 or 2.");
            continue;
        }

        let continue_input = get_user_input_str("Do you want to continue converting? (y/n): ");
        if continue_input.trim().eq_ignore_ascii_case("n") {
            println!("Goodbye!");
            break;
        }
    }
}

fn convert_to_celsius(fahrenheit: f32) -> f32 {
    (fahrenheit - 32.0) * 5.0 / 9.0
}

fn convert_to_fahrenheit(celsius: f32) -> f32 {
    celsius * 9.0 / 5.0 + 32.0
}

fn get_user_input(prompt: &str) -> f32 {
    loop {
        let mut input = String::new();
        println!("{}", prompt);
        io::stdin().read_line(&mut input).expect("Failed to read line");
        match input.trim().parse() {
            Ok(num) => return num,
            Err(_) => println!("Invalid input. Please enter a valid number."),
        }
    }
}

fn get_user_input_str(prompt: &str) -> String {
    let mut input = String::new();
    println!("{}", prompt);
    io::stdin().read_line(&mut input).expect("Failed to read line");
    input.trim().to_string()
}

Step-by-Step Breakdown

1. Imports and the main Function

use std::io;

fn main() {
    println!("Hello, Rust Chapter 3!");
  • use std::io;: This line imports Rust’s standard input/output library, which we’ll use to handle user input.
  • fn main(): The main function is the entry point of every Rust program. Here, we start by printing a greeting message using println!.

2. Infinite Loop and User Choice

    loop {
        let what_to_do = get_user_input("Enter 1 to convert from Celsius to Fahrenheit, or 2 to convert from Fahrenheit to Celsius: ");
  • loop {}: This is an infinite loop. The program will repeatedly ask the user for input until they decide to quit.
  • get_user_input(...): We call a helper function (defined later) to get the user’s choice. This function reads input and returns it as a f32 (floating-point number).

3. Handling User Input

        if what_to_do == 1.0 {
            let celsius = get_user_input("Enter the temperature in Celsius: ");
            let fahrenheit = convert_to_fahrenheit(celsius);
            println!("{} Celsius is {} Fahrenheit.", celsius, fahrenheit);
        } else if what_to_do == 2.0 {
            let fahrenheit = get_user_input("Enter the temperature in Fahrenheit: ");
            let celsius = convert_to_celsius(fahrenheit);
            println!("{} Fahrenheit is {} Celsius.", fahrenheit, celsius);
        } else {
            println!("Invalid input. Please enter 1 or 2.");
            continue;
        }
  • if/else if/else Statements: These statements determine what action to take based on the user’s input.
    • If the user enters 1, the program converts Celsius to Fahrenheit.
    • If the user enters 2, it converts Fahrenheit to Celsius.
    • If the input is invalid (neither 1 nor 2), the program prompts the user again.

4. Converting Temperatures

fn convert_to_celsius(fahrenheit: f32) -> f32 {
    (fahrenheit - 32.0) * 5.0 / 9.0
}

fn convert_to_fahrenheit(celsius: f32) -> f32 {
    celsius * 9.0 / 5.0 + 32.0
}
  • These functions perform the actual temperature conversion.
  • convert_to_celsius: Converts Fahrenheit to Celsius using the formula (Fahrenheit - 32) * 5/9.
  • convert_to_fahrenheit: Converts Celsius to Fahrenheit using the formula Celsius * 9/5 + 32.

5. Getting User Input

fn get_user_input(prompt: &str) -> f32 {
    loop {
        let mut input = String::new();
        println!("{}", prompt);
        io::stdin().read_line(&mut input).expect("Failed to read line");
        match input.trim().parse() {
            Ok(num) => return num,
            Err(_) => println!("Invalid input. Please enter a valid number."),
        }
    }
}

fn get_user_input_str(prompt: &str) -> String {
    let mut input = String::new();
    println!("{}", prompt);
    io::stdin().read_line(&mut input).expect("Failed to read line");
    input.trim().to_string()
}
  • get_user_input: This function repeatedly prompts the user until they enter a valid number.
    • String::new(): Creates a new, empty String to hold the user’s input.
    • io::stdin().read_line(&mut input): Reads a line of input from the user.
    • input.trim().parse(): Attempts to parse the trimmed input into a floating-point number (f32).
    • match input.trim().parse(): If parsing is successful, it returns the number; otherwise, it prints an error message and prompts again.
  • get_user_input_str: Similar to get_user_input, but this function returns a String instead of a number. It’s used for handling textual inputs, like “y” or “n”.

6. Continuing or Exiting the Loop

        let continue_input = get_user_input_str("Do you want to continue converting? (y/n): ");
        if continue_input.trim().eq_ignore_ascii_case("n") {
            println!("Goodbye!");
            break;
        }
    }
}
  • After each conversion, the program asks the user if they want to continue.
  • eq_ignore_ascii_case("n"): Checks if the user entered “n” (case insensitive). If so, the loop breaks, and the program ends with a “Goodbye!” message.

Conclusion

By following this tutorial, you’ve built a simple yet functional temperature converter in Rust programming. Through this process, you’ve learned about Rust’s syntax, functions, loops, conditional statements, and user input handling. This project is a great way to get your feet wet with Rust and understand its fundamental concepts.

If you want to learn more about Rust programming, check out the official Rust documentation, which is an excellent resource for beginners and experienced developers alike. Keep experimenting, and don’t hesitate to modify this program to explore other Rust features!

Happy coding!

Rust Programming: Start with This Simple Number Guessing Game Tutorial

Rust

Rust Programming Introduction: Getting Started

Rust is a systems programming language that has been gaining a lot of traction due to its performance, safety, and concurrency capabilities. Despite being a systems language, Rust can be very approachable for beginners. In this tutorial, we’ll walk through the process of building a simple command-line number guessing game in Rust. This guide is perfect for those who are just starting out with Rust and want to understand some of its basic concepts.

What We Will Build in Rust Programming

We will build a simple game where the computer randomly generates a secret number between 1 and 100, and the player has to guess it. The program will provide feedback on whether the guess is too low, too high, or correct. The game will continue until the player guesses the correct number.

Prerequisites

Before you start, ensure you have the following:

  • Rust Installed: If you haven’t installed Rust yet, you can do so by following the instructions on the official Rust website. You’ll be using cargo, Rust’s package manager, to manage and run your projects.

Step 1: Setting Up Your Rust Programming Environment

  1. Install Rust:
  • Rust can be installed via rustup, a command-line tool for managing Rust versions and associated tools.
  • On Unix-based systems (Linux, macOS), run the following command in your terminal: curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
  • On Windows, download and run the rustup-init.exe file.
  • Follow the on-screen instructions to complete the installation.
  1. Verify the Installation:
  • To ensure Rust is installed correctly, run: rustc --version
  • You should see the version number of Rust that is installed.

Step 2: Creating a New Rust Project

Now that Rust is installed, let’s create a new project.

  1. Create a New Project:
  • Use the cargo command to create a new project: cargo new guessing_game cd guessing_game
  • This command creates a new directory named guessing_game with a Cargo.toml file and a src directory containing a main.rs file.
  1. Open the Project:
  • Open the guessing_game directory in your favorite text editor or IDE. The main.rs file is where we’ll write our code.

Step 3: Writing the Number Guessing Game

Let’s dive into the code. Below is the complete code for the number guessing game:

The Code

extern crate rand;

use std::io;
use std::cmp::Ordering;
use rand::Rng;

fn main() {
    println!("Guess the number!");
    let secret_number = rand::thread_rng().gen_range(1..101);
    println!("The secret number is {}", secret_number);
    loop{
    println!("Please input your guess.");
    let mut guess = String::new(); // this is a mutable variable which can be changed
    let my_number: i8 = 10; // this can not change value of this variable, or it will be an error
    io::stdin().read_line(&mut guess).expect("Failed to read line"); // this line is to read user input
    let guess : u8 = match guess.trim().parse(){
        Ok(num) => {num},
        Err(_) => continue,
    };
    println!("My Number is {}", my_number); // this line is to print my number
    println!("You guessed {}", guess); // this line is to print user input
    match guess.cmp(&secret_number) {
        Ordering::Less => println!("Too small!"),
        Ordering::Greater => println!("Too big!"),
        Ordering::Equal => {
            println!("You win!");
            break;
        },
    }
    if guess == secret_number {
        println!("You win from if Condition!");
    }
    else {
        println!("You lose!");
    }
    }

}

Explanation

  1. Imports:
    • extern crate rand; brings in the external rand crate, which is used to generate random numbers.
    • use std::io; brings in the I/O (input/output) module from the standard library, which we will use to handle user input.
    • use std::cmp::Ordering; is used for comparing values.
    • use rand::Rng; allows us to use the random number generation capabilities provided by the rand crate.
  2. Main Function:
    • We start by printing a welcome message to the console with println!("Guess the number!");.
    • The secret number is generated using rand::thread_rng().gen_range(1..101);, which produces a random number between 1 and 100.
    • We then enter an infinite loop with loop {} to continually prompt the user for input until they guess correctly.
    • Inside the loop:
      • let mut guess = String::new(); creates a mutable string that will hold the user’s guess.
      • io::stdin().read_line(&mut guess).expect("Failed to read line"); reads the user’s input from the standard input and stores it in the guess variable.
      • let guess : u8 = match guess.trim().parse(){...}; converts the input string into a number, handling any errors that might occur if the input isn’t a valid number.
      • We then compare the user’s guess with the secret number using match guess.cmp(&secret_number), printing appropriate messages depending on whether the guess was too low, too high, or correct.
      • If the guess is correct, we break out of the loop, ending the game.
  3. Comments:
    • Throughout the code, comments explain what each part does. These comments are essential for beginners to understand the purpose of each line and block of code.

Step 4: Running Your Program

Once you’ve written the code, it’s time to run your game.

  1. Run the Game:
  • In your terminal, make sure you’re in your project directory and simply type: cargo run
  • This will compile and run your Rust program. You’ll see the message “Guess the number!” printed in your terminal.
  1. Interact with the Game:
  • Enter a guess when prompted. The program will tell you whether your guess is too low, too high, or correct.
  • The game will continue until you guess the correct number, at which point it will congratulate you and end.

Conclusion

Congratulations! You’ve successfully created a simple number guessing game in Rust. Through this tutorial, you’ve learned how to set up a Rust environment, write and run a Rust program, and use basic Rust constructs like loops, conditionals, and input/output handling.

This project is a great introduction to Rust’s syntax and capabilities. As you continue your journey with Rust, you’ll discover more advanced features and tools that make Rust a powerful language for systems programming, web development, and beyond.

Don’t stop here—keep experimenting with Rust by adding more features to this game or exploring other projects. Happy coding!

Rust programming, number guessing game, Rust tutorial, beginner Rust project, command-line game, Rust basics, coding game tutorial