gh_mirrors/ru/rust-by-example项目实战:构建你的第一个Rust应用

【免费下载链接】rust-by-example Learn Rust with examples (Live code editor included) 【免费下载链接】rust-by-example 项目地址: https://gitcode.com/gh_mirrors/ru/rust-by-example

你还在为学习Rust找不到合适的入门实践而烦恼吗?本文将带你通过gh_mirrors/ru/rust-by-example项目,从零开始构建第一个Rust应用,让你快速掌握Rust基础语法与项目构建流程。读完本文,你将学会如何使用Cargo创建项目、编写Hello World程序、处理变量绑定以及进行简单的流程控制。

准备工作:了解项目结构

gh_mirrors/ru/rust-by-example项目是一个通过实例学习Rust的优质资源,包含丰富的代码示例和交互式编辑器。项目核心内容位于src/目录下,其中src/hello.md是入门首选,src/cargo.md则详细介绍了Rust的包管理工具Cargo。

首先,克隆项目到本地:

git clone https://gitcode.com/gh_mirrors/ru/rust-by-example.git
cd rust-by-example

第一步:创建你的第一个Rust程序

Hello World基础实现

打开src/hello.md,可以看到经典的Hello World程序实现:

// 这是单行注释,编译器会忽略它
// 主函数,程序入口点
fn main() {
    // 向控制台输出文本
    println!("Hello World!");
}

上述代码中,fn main()定义了程序的入口函数,println!是Rust的宏(Macro)用于打印输出。通过rustc hello.rs命令可编译生成可执行文件,执行后将在控制台显示"Hello World!"。

扩展功能:添加自定义输出

按照src/hello.md中的练习指导,添加第二行输出语句:

fn main() {
    println!("Hello World!");
    println!("I'm a Rustacean!"); // 添加此行
}

编译运行后,输出将变为:

Hello World!
I'm a Rustacean!

第二步:使用Cargo管理项目

Cargo简介

src/cargo.md详细介绍了Cargo的功能,它是Rust的官方包管理工具,支持依赖管理、单元测试和基准测试等功能。使用Cargo可以更高效地管理Rust项目。

创建Cargo项目

在终端中执行以下命令创建新的Cargo项目:

cargo new my_first_rust_app
cd my_first_rust_app

Cargo会自动生成项目结构,其中src/main.rs是程序入口文件,内容如下:

fn main() {
    println!("Hello, world!");
}

构建与运行项目

使用cargo run命令可以一键编译并运行项目:

cargo run

输出结果:

Hello, world!

第三步:变量绑定与数据类型

变量声明与使用

在Rust中,使用let关键字声明变量。打开src/variable_bindings/declare.md,学习变量的基本用法:

fn main() {
    let x = 5; // 声明不可变变量
    println!("x的值为: {}", x);
}

若需要修改变量值,需使用mut关键字声明可变变量:

fn main() {
    let mut x = 5;
    x = 6; // 合法,因为x是可变的
    println!("x的值变为: {}", x);
}

基本数据类型

Rust提供多种基本数据类型,如整数、浮点数、布尔值和字符。查看src/primitives.md了解更多细节:

fn main() {
    let integer = 42; // i32类型
    let float = 3.14; // f64类型
    let boolean = true; // bool类型
    let character = 'a'; // char类型
    println!("整数: {}, 浮点数: {}, 布尔值: {}, 字符: {}", integer, float, boolean, character);
}

第四步:流程控制

条件语句

src/flow_control/if_else.md介绍了条件语句的使用:

fn main() {
    let number = 7;
    if number % 2 == 0 {
        println!("{}是偶数", number);
    } else {
        println!("{}是奇数", number);
    }
}

循环语句

Rust提供多种循环方式,如loopwhilefor。查看src/flow_control/loop.mdsrc/flow_control/for.md

// loop循环
fn main() {
    let mut count = 0;
    loop {
        count += 1;
        if count == 3 {
            break; // 跳出循环
        }
        println!("计数: {}", count);
    }
}

// for循环
fn main() {
    let numbers = [1, 2, 3, 4, 5];
    for number in numbers.iter() {
        println!("数字: {}", number);
    }
}

总结与后续学习

通过本文的学习,你已经掌握了Rust的基本语法、Cargo项目管理、变量绑定和流程控制等知识。接下来,你可以继续深入学习以下内容:

希望本文能帮助你顺利入门Rust开发,持续关注项目README.md获取更多学习资源。如果你觉得本文有用,请点赞、收藏并分享给其他Rust学习者!

【免费下载链接】rust-by-example Learn Rust with examples (Live code editor included) 【免费下载链接】rust-by-example 项目地址: https://gitcode.com/gh_mirrors/ru/rust-by-example

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐