前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >成为大模型参与者第一天:导学阶段 - 人工智能与大模型基础知识:完成Rust基础题目

成为大模型参与者第一天:导学阶段 - 人工智能与大模型基础知识:完成Rust基础题目

作者头像
早起的鸟儿有虫吃
发布于 2025-04-11 04:51:58
发布于 2025-04-11 04:51:58
4900
代码可运行
举报
运行总次数:0
代码可运行

InfiniTensor 是基于清华大学高性能所科研团队建立的开源组织,

主要研究领域包括人工智能编译器、大模型推理系统和国产硬件的生态建设。

rustlings是一个rustOJ形式的学习平台,通过90多道题目来测试rust语法的掌握程度,第一次接触的时候会感觉非常新颖,通过rustlings进行学习也非常高效。

我的任务:

学员晋级条件:

学员在基础阶段可选Rust基础或C++基础完成习题,将一个方向的习题完成并满分即可晋级专业阶段。

我直接ai完成这个题目。

行动1: 开发环境 搭建

Installing Rust

Rust开发时有时使用官方的源太慢,可以考虑更换使用国内的源

字节跳动搞的,希望能帮助建设国内的 rust 生态,感兴趣的话可以试用,无任何限速(实际上是 1000Gbps)。

地址:https://rsproxy.cn/

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
## rust开发环境设置
步骤一:设置 Rustup 镜像
export RUSTUP_DIST_SERVER="https://rsproxy.cn"
export RUSTUP_UPDATE_ROOT="https://rsproxy.cn/rustup"
source ~/.bashrc

步骤二:安装 Rust
curl --proto '=https' --tlsv1.2 -sSf https://rsproxy.cn/rustup-init.sh | sh

检查安装是否成功
rustc -V
rustc 1.86.0-nightly (4a4309466 2025-02-02)

rustup component add clippy

rustup component add rustfmt

检查安装是否成功Rust 本地文档的使用:rustup docRust 是一种系统级编程语言,以其安全性、速度和内存控制能力而闻名。为了方便开发者更好地了解并利用 Rust 标准库和工具链中的功能,Rust 提供了一种内置的文档浏览方式——通过 rustup doc 命令安装 Rust 的同时也会在本地安装一个文档服务 ,方便我们离线阅读:运行 rustup doc 让浏览器打开本地文档。

rustup component add --toolchain nightly-x86_64-apple-darwin rust-docs

rustup doc

Rust官方提供了完善的开发工具链。

简单介绍如下:

  • rustup:工具链管理器。用于工具链软件的切换和升级。
  • rustc:编译器。
  • cargo:项目和包管理器
  • xargo:扩展版cargo,支持使用自定义的std库。开发OS必备

来源:

  • https://wangrunji0408.gitbooks.io/rustos/content/lab0/toolchain.html

如果你想直接打开特定组件(如标准库)的文档:

rustup doc std

若要查看 Rust 语言参考(The Rust Reference):

rustup doc reference

开发工具:

Our general recommendation is VS Code with the rust-analyzer plugin.

行动2:Exam Grading 自动测试评分系统使用教程

参考资料:

  • https://github.com/LearningInfiniTensor/.github/blob/main/exam-grading-user-guide/doc.md
  • https://rustlings.cool/

按此教程操作,完成构建自己的评测系统用于后续阶段的测验提交,并熟悉评测系统的使用。

下列步骤完成了 3 项工作:

  1. 准备 Git 环境
  2. 获取 exam-grading 源码
  3. 测验评分

步骤: (我在mac上直接开发)

1. 准备 Git 环境

Git 的安装可参考:

1.5 起步 - 安装 Git 或 InfiniTensor 训练营导学阶段指导书

~/.gitconfig

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
[core]
        autocrlf = input
[user]
        email = wang_cyi@163.com
        name = watchpoints
[credential]

2. 获取exam-grading源码

学员需要通过 exam-grading模板 创建自己的评分系统仓库:

NOTICE 推荐创建为private仓库

之后将创建的exam-grading仓库拉取到本地

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
git clone <repo-addr> ./exam-grading
cd exam-grading


git clone git@github.com:watchpoints/rust-learn.git ./exam-grading
  1. 下载练习题目:

基础阶段的使用

同样按照[以上步骤](#步骤)的前两步准备环境和创建仓库并克隆到本地,之后在 exam-grading 项目根目录中添加测试目录:

方式1 直接目录:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
# 将learning-cxx克隆到exam-grading目录外(也就是exam-grading的同级目录)
git clone <target-test-repo> ./learning-cxx
cd learning-cxx
# 确保为最新
git pull
# 然后将目录复制进exam-grading

# 将rustlings克隆到exam-grading目录外(也就是exam-grading的同级目录)
git clone <target-test-repo> ./rustlings

git clone git@github.com:watchpoints/rustlings-zh-cn.git ./rustlings

cd rustlings
# 确保为最新
git pull
# 然后将目录复制进exam-grading


https://github.com/cicvedu/rustlings-semester-4-watchpoints/tree/main/exercises

NOTICE 目标测试目录中存在 .git 目录可能会导致问题,删除后再试

方式2:子模块:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
# learning-cxx
git submodule add <target-test-repo> ./learning-cxx

# rustlings
git submodule add <target-test-repo> ./rustlings

# 确保为最新
git submodule update --remote

NOTICE learning-cxxrustlings 目录名写死,否则检测不到,不会执行对应评分。

方式3: 最简单的方式

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
https://rustlings.cool/

rustlings init

cd rustlings
# 确保为最新
git pull
# 然后将目录复制进exam-grading

直接目录:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
# 将 TinyInfiniTensor 克隆到 exam-grading 目录外(也就是 exam-grading 的同级目录)
git clone <target-test-repo> ./TinyInfiniTensor
cd TinyInfiniTensor
# 确保为最新
git pull
# 然后将目录复制进 exam-grading

# 将 learning-lm-rs 克隆到 exam-grading 目录外(也就是 exam-grading 的同级目录)
git clone <target-test-repo> ./learning-lm-rs
cd learning-lm-rs
# 确保为最新
git pull
# 然后将目录复制进 exam-grading

NOTICE 目标测试目录中存在 .git 目录可能会导致问题,删除后再试

子模块:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
# TinyInfiniTensor
git submodule add <target-test-repo> ./TinyInfiniTensor

# learning-lm-rs
git submodule add <target-test-repo> ./learning-lm-rs

# 确保为最新
git submodule update --remote

NOTICE TinyInfiniTensorlearning-lm-rs 目录名写死,否则检测不到,不会执行对应评分。

可在子模块内直接做题,之后先提交子模块仓库,再提交 exam-grading 的即可。

也可选择在其它位置完成题目后,通过直接目录形式复制进 exam-grading 提交评分,

或通过子模块方法添加目录后提交评分。

行动3:rust学习之路——rustlings练习题

做题顺序

rustlings run

  • 使用包、Crate 和模块管理不断增长的项目
  • Option 枚举类型来实现

https://rustwiki.org/zh-CN/rust-by-example/std/option.html

何时使用 ref

场景

匹配方式

是否移动所有权

Some(p)

match optional_point

✅ 移动

Some(ref p)

match optional_point

❌ 不移动

Some(p)

match &optional_point

❌ 不移动

在 Rust 的 match 语句中,ref 关键字的作用是 创建引用,而不会移动所有权。 让我们详细拆解 Some(ref p) 的含义。


  1. 为什么需要 ref

match 语句中,默认情况下模式匹配会 移动 变量的所有权。例如:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
let optional_point = Some(Point { x: 100, y: 200 });
match optional_point {
    Some(p) => println!("Co-ordinates are {},{}", p.x, p.y), // ❌ 这里会移动 
Point
    _ => panic!("No match!"), } println!("{optional_point:?}"); // ❌ 编译错误!optional_point 已被移动

编译错误的原因:

  • Some(p) 会将 Point 的所有权移动p,导致 optional_point 失效。
  • 由于 optional_point 仍然在 println! 语句中使用,Rust 不允许使用已被移动的变量

  1. 解决方案:使用 ref 关键字
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
match optional_point {
    Some(ref p) => println!("Co-ordinates are {},{}", p.x, p.y), // ✅ 这里 
p
 只是引用,不移动    _ => panic!("No match!"), }

Some(ref p) 的作用:

  • ref p 不会移动 Point,而是创建一个 Point 的引用 p
  • 这样,optional_point 仍然保持所有权,可以在 println! 语句中继续使用。

3. ref 的等价写法

其实,我们也可以使用 match 绑定一个引用,而不使用 ref

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
match &optional_point {
    Some(p) => println!("Co-ordinates are {},{}", p.x, p.y), // ✅ 这里 
p
 直接是引用    _ => panic!("No match!"), }

区别:

  • match optional_point 直接匹配 Some(ref p)pPoint 的引用)。
  • match &optional_point 直接匹配 Some(p),因为 &optional_point 本身就是 &Option<Point>

  1. 何时使用 ref

场景

匹配方式

是否移动所有权

Some(p)

match optional_point

✅ 移动

Some(ref p)

match optional_point

❌ 不移动

Some(p)

match &optional_point

❌ 不移动

推荐:

  • 如果想要 借用 而不是 移动 变量,使用 Some(ref p)match &optional_point
  • match &optional_point 更符合现代 Rust 习惯,推荐使用。

完整修正代码

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
#[derive(Debug)]
struct Point {
    x: i32,
    y: i32,
}
fn main() {
    let optional_point = Some(Point { x: 100, y: 200 });
    // 使用 
match &optional_point
 代替Some(ref p)
    match &optional_point {        Some(p) => println!("Co-ordinates are {},{}", p.x, p.y),        _ => panic!("No match!"),    }    println!("{optional_point:?}"); // ✅ 仍然可以使用 }

运行结果:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
Co-ordinates are 100,200
Some(Point { x: 100, y: 200 })

🚀 总结:

  • Some(ref p) 在匹配时借用值,而不是移动。
  • 推荐使用 match &optional_point,更加符合 Rust 习惯。

学习过程

Options

有时候想要捕捉到程序某部分的失败信息,而不是调用 panic!

这可使用 Option 枚举类型来实现。

Option<T> 有两个变量:

  • None,表明失败或缺少值
  • Some(value),元组结构体,封装了一个 T 类型的值 valu

Further information

  • Error Handling
  • Generics
  • Result
  • Boxing errors

use std::fs::File;

fn main() {

let greeting_file_result = File::open("hello.txt");

let greeting_file = match greeting_file_result {

Ok(file) => file,

Err(error) => panic!("Problem opening the file: {error:?}"),

};

}

Generics

Generics is the topic of generalizing types and functionalities to broader cases.

This is extremely useful for reducing code duplication in many ways, but can call for some rather involved syntax.

Namely, being generic requires taking great care to specify over which types a generic type is actually considered valid.

The simplest and most common use of generics is for type parameters.

Further information

  • Generic Data Types
  • Bounds

Traits

A trait is a collection of methods.

Data types can implement traits. To do so, the methods making up the trait are defined for the data type. For example, the String data type implements the From<&str> trait. This allows a user to write String::from("hello").

In this way, traits are somewhat similar to Java interfaces and C++ abstract classes.

Some additional common Rust traits include:

  • Clone (the clone method)
  • Display (which allows formatted display via {})
  • Debug (which allows formatted display via {:?})

Because traits indicate shared behavior between data types, they are useful when writing generics.

Further information

  • Traits

Lifetimes

Lifetimes tell the compiler how to check whether references live long

enough to be valid in any given situation. For example lifetimes say

"make sure parameter 'a' lives as long as parameter 'b' so that the return

value is valid".

They are only necessary on borrows, i.e. references,

since copied parameters or moves are owned in their scope and cannot

be referenced outside. Lifetimes mean that calling code of e.g. functions

can be checked to make sure their arguments are valid. Lifetimes are

restrictive of their callers.

If you'd like to learn more about lifetime annotations, the

lifetimekata project

has a similar style of exercises to Rustlings, but is all about

learning to write lifetime annotations.

Further information

  • Lifetimes (in Rust By Example)
  • Validating References with Lifetimes

Iterators

This section will teach you about Iterators.

Further information

  • Iterator
  • Iterator documentation

Smart Pointers

In Rust, smart pointers are variables that contain an address in memory and reference some other data, but they also have additional metadata and capabilities.

Smart pointers in Rust often own the data they point to, while references only borrow data.

Further Information

  • Smart Pointers
  • Using Box to Point to Data on the Heap
  • Rc\<T\>, the Reference Counted Smart Pointer
  • Shared-State Concurrency
  • Cow
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2025-02-15,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 后端开发成长指南 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验