Rust之初识

1、Rust Linux安装

    登录进入linux以后,执行: curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh当提示: Rust is installed now. Great!意味着安装成功了。打开另一个shell页,查看:rustc --version,看到版本即可。

2、文件、编译、运行

Rust文件是以.rs结尾:
        如:main.rs、hello_app.rs等

创建一个Rust项目:
        cargo new projectName

执行命令: cargo new a-1之后,创建了工程a-1,目录结构如下:
a-1/
├── Cargo.toml
└── src└── main.rs
1 directory, 2 files

Cargo.toml : Cargo作为rust的包管理程序,就是通过这个文件知道你这个项目中需要哪些依赖库。如果你想要用到某些库,直接写在[dependencies]项的下面即可。该文件包含内容如下:

[package]
name = "a-1"
version = "0.1.0"
edition = "2021"[dependencies]

运行一个Rust项目:

        cd a-1/

        cargo run    【编译并运行当前项目】

编译一个Rust项目:

        cargo build                       【默认构建的是Debug版本,生成文件相对较大】

        cargo build --release      【构建Release版本,生成文件相对较小】

3、语法

3.1、变量

        Rust中声明变量的方式非常简单,只有三个关键字:letmutconst,对应着三种形式的变量。

声明不可变变量:

fn main() {let a1=10;//a1=20;//出错
}

声明可变变量:

fn main() {let mut a1=10;a1=20;
}

声明常量:

fn main() {const a1:i32=10;
}

注意:

        (1)常量名称后面必须紧跟变量的类型,比如这里的 :i32。

        (2)const 后面不可以添加mut关键字使它可变。

代码:

fn main() {let a1 = 10;println!("===== a1={}", a1);//a1=20;let mut a2 = 399;println!("===== a2={}", a2);a2 = 499;println!("===== a2={}", a2);let a2 = "cffg";println!("===== a2={}", a2);//a2 = 99; // 出错,a2不可更改
}

结果:

   Compiling a-1 v0.1.0 (/home/test/rust/a-1)Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.15sRunning `target/debug/a-1`
===== a1=10
===== a2=399
===== a2=499
===== a2=cffg

3.2、数据类型

        Rust中的数据类型分为两种:标量(scalar)和 复合(compound)。

标量:

        标量分为四种:整型、浮点型、布尔类型和字符类型。

(1)整型

长度有符号无符号
8-biti8u8
16-biti16u16
32-biti32u32
64-biti64u64
128-biti128u128
archisizeusize

        最后的一行archisizeusize,则代表它的大小取决去当前系统架构,如果为x86,则它等同于i32u32,如果为x64,则它等同于i64u64。

(2)浮点型

长度类型
32-bitf32
64-bitf64

(3)bool型

        只有两个可选值:truefalse;而不是1与0。

(4)字符类型

        主要用于表示一个字符。

fn bb_fun() {let b1:i32 = 100;println!("===== b1={}", b1);let b2:f32 = 100.0;println!("===== b2={}", b2);let b3:bool = true;println!("===== b3={}", b3);let a1:char = 'K';println!("===== a1={}", a1);let a2:char = '好';println!("===== a2={}", a2);
}fn main() {let a1 = 10;println!("===== a1={}", a1);//a1=20;let mut a2 = 399;println!("===== a2={}", a2);a2 = 499;println!("===== a2={}", a2);let a2 = "cffg";println!("===== a2={}", a2);//a2 = 99; // 出错,a2不可更改bb_fun();
}

结果:

   Compiling a-1 v0.1.0 (/home/work/test/rust/a-1)Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.14sRunning `target/debug/a-1`
===== a1=10
===== a2=399
===== a2=499
===== a2=cffg
===== b1=100
===== b2=100
===== b3=true
===== a1=K
===== a2=好

复合:

        Rust 有两个原生的复合类型:元组(tuple)、数组(array)、结构体(struct)。

(1)tuple

        它通过小括号包含一组表达式构成。tuple内的元素是没有名字的,可以将多个不同的数据类型放在一起组成。

代码:

fn main() {let tup=(100,'余',true,10.1);// 等价于 let tup:(i32, char, bool, f64)=(100,'余',true,10.1);println!("{} {} {} {}",tup.0,tup.1,tup.2,tup.3);
}

结果:

   Compiling a-1 v0.1.0 (/home/test/rust/a-1)Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.14sRunning `target/debug/a-1`
100 余 true 10.1

(2)数组

        数组中的所有元素的类型必须相同。

代码:

fn main() {let arr=[1,2,3,4,5,6,7,8];println!("{} {} {} {}",arr[0],arr[1],arr[2],arr[3]);
}

结果:

   Compiling a-1 v0.1.0 (/home/test/rust/a-1)Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.14sRunning `target/debug/a-1`
1 2 3 4

(3)结构体

        它通过大括号包含一组表达式构成。tuple内的元素是由自己名字的,可以将多个不同的数据类型放在一起组成。

代码:

struct Base 
{x:i32,y:i32,
}fn main() {let p = Base{x:3, y:32};println!("p is at {} {}", p.x, p.y);}

结果:

   Compiling a-1 v0.1.0 (/home/test/rust/a-1)Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.13sRunning `target/debug/a-1`
p is at 3 32

3.3、函数

最简单的函数:  无输入、无输出
fn simple(){}函数调用:
fn main() {simple();
}
有输入的函数:  有输入(从函数外部传入的变量)、无输出
fn simple(i:i32, c:char, f:f64, b:bool){println!("{} {} {} {}", i, c, f, b);
}函数调用:
fn main() {simple(100, 'c', 3.1415, true);
}
有输入、输出的函数:  有输入(从函数外部传入的变量)、有输出(内部有返回值)
fn simple(i:i32, c:char, f:f64, b:bool){println!("{} {} {} {}", i, c, f, b);return i + 10;
}函数调用:
fn main() {let s = simple(100, 'c', 3.1415, true);println!("==== s={}", s);
}

3.4、注释

fn main() {// abcedf/*abcdeffadasdadsadas*/let p = 398;
}

3.5、控制流

(1)if、else if、else

fn main() {let a = 10;if a > 0 {println!("a > 0");} else if a == 0 {println!("a == 0");} else {println!("a < 0");}
}

结果:

   Compiling a-1 v0.1.0 (/home/test/rust/a-1)Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.14sRunning `target/debug/a-1`
a > 0

(2)loop、break

        无限循环,使用break退出循环。

fn main() {let mut a = 10;loop {a = a + 1;println!("{}", a);if a > 20 {break;}}
}

结果:

   Compiling a-1 v0.1.0 (/home/test/rust/a-1)Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.14sRunning `target/debug/a-1`
11
12
13
14
15
16
17
18
19
20
21

(3)while

fn main() {let mut a = 10;while a!=20 {              // 如果写成 a != 20 会报错,不知道为什么println!("{}", a);a = a + 1;}
}// 范围运算符 ..生成的范围对象是左闭右开的,具体来说,10..20 ,i只会等于10到19

结果:

   Compiling a-1 v0.1.0 (/home/test/rust/a-1)Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.13sRunning `target/debug/a-1`
10
11
12
13
14
15
16
17
18
19

(4)for

fn main() {for i in 10..20{println!("{}", i);}
}

结果:

   Compiling a-1 v0.1.0 (/home/test/rust/a-1)Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.14sRunning `target/debug/a-1`
10
11
12
13
14
15
16
17
18
19

3.6、运算符

(1)算术运算符

+返回操作数之和
-返回操作数之差
*返回操作数乘积
/执行除法运算并返回商
%执行除法运算并返回余数

(2)关系运算符

>
<
>=
<=
==
!=

(3)逻辑运算符

&&(And)
||(OR)
!(NOT)

(4)按位运算符

&(按位与)
|(按位或)
^(按位异或)
!(按位取反)
<<(左移)
>>(右移)
>>>(右移为零)

4、包管理

        如果想使用到ferris-says这个库,首先来到前面提到的Cargo.toml文件,然后在[dependencies]项添加这个库,重新编译即可。

[package]
name = "a-1"
version = "0.1.0"
edition = "2021"[dependencies]
ferris-says = "0.2"
[root@local_tmp]# cargo buildUpdating crates.io index
warning: spurious network error (3 tries remaining): [28] Timeout was reached (failed to download any data for `ferris-says v0.2.1` within 30s)
warning: spurious network error (3 tries remaining): [28] Timeout was reached (download of `smallvec v0.4.5` failed to transfer more than 10 bytes in 30s)Downloaded smawk v0.3.2Downloaded unicode-width v0.1.12Downloaded smallvec v0.4.5Downloaded textwrap v0.13.4Downloaded ferris-says v0.2.1Downloaded 5 crates (106.0 KB) in 1m 04sCompiling smawk v0.3.2Compiling unicode-width v0.1.12Compiling smallvec v0.4.5Compiling textwrap v0.13.4Compiling ferris-says v0.2.1Compiling a-1 v0.1.0 (/home/test/rust/a-1)Finished `dev` profile [unoptimized + debuginfo] target(s) in 1m 08s

代码:

use ferris_says::say; // from the previous step
use std::io::{stdout, BufWriter};fn main() {let stdout = stdout();let message = String::from("Hello fellow Rustaceans!");let width = message.chars().count();let mut writer = BufWriter::new(stdout.lock());say(message.as_bytes(), width, &mut writer).unwrap();
}

结果:

   Compiling a-1 v0.1.0 (/home/work/rust/a-1)Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.35sRunning `target/debug/a-1`__________________________
< Hello fellow Rustaceans! >--------------------------\\_~^~^~_\) /  o o  \ (/'_   -   _'/ '-----' \

5、module

5.1、用mod关键字定义模块【类似于C++的#include】

// 文件名:src/main.rs
mod greeting {pub fn say_hello()  {println!("Hello, world!");}
}fn main() {greeting::say_hello();
}

结果:

[root@local_tmp]# cargo runCompiling a-1 v0.1.0 (/home/test/rust/a-1)Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.15sRunning `target/debug/a-1`
Hello, world!

        mod 关键词定义了一个模块,看起来像 c++ 的 namespace。

注意:

        say_hello 前面加上了 pub 关键字,表示这个函数是公开的。如果不加这个符号的话,函数只能在模块 greeting 内部使用。

5.2、用单独的文件定义模块

// 文件名:src/greeting.rs
pub fn say_hello()  {println!("Hello, world!");
}// 文件名:src/main.rs
mod greeting;fn main() {greeting::say_hello();
}

结果:

[root@local_tmp]# cargo runCompiling a-1 v0.1.0 (/home/test/rust/a-1)Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.15sRunning `target/debug/a-1`
Hello, world!

5.3、用文件夹定义模块

// 文件名:src/greeting/morning.rs
pub fn good_morning() {println!("Good morning!");// 文件名:src/greeting/night.rs
pub fn good_night() {println!("Good night!");
}// 文件名:src/greeting/mod.rs: 只有存在这个文件,当前文件夹才能成为 module。
pub mod morning;
pub mod night;// 文件名:src/main.rs
mod greeting;
fn main() {greeting::morning::good_morning();greeting::night::good_night();
}

5.4、use ......

        可以使用 use 简化引用路径,这一点类似 c++ 的 using namespace。上面的 main.rs 可以改写如下:

mod greeting;
use greeting::morning;
use greeting::night::*;fn main() {morning::good_morning();good_night();
}

6、库文件【依赖第三方库时使用】

(1)创建工程

        执行如下命令,创建工程;

cargo new aabbcc
cargo new aabbcclib --lib

会生成aabbcc、aabbcclib两个目录。

[root@local_tmp]#
[root@local_tmp]# tree aabbcc
aabbcc
├── Cargo.toml
└── src└── main.rs1 directory, 2 files
[root@local_tmp]#
[root@local_tmp]# tree aabbcclib/
aabbcclib/
├── Cargo.toml
└── src└── lib.rs1 directory, 2 files
[root@local_tmp]# 

其中 aabbcc是可执行文件,aabbcclib 是库文件。我们如何调用库文件中的函数?

(2)源代码

// 文件名:aabbcclib/src/lib.rs
pub fn say() {println!("hello word!");
}// 文件名:aabbcc/src/main.rs
extern crate aabbcclib;
fn main() {aabbcclib::say();
}// 文件名:aabbcc/Cargo.toml: 添加依赖项 aabbcclib = { path = "../aabbcclib"}
[package]
name = "aabbcc"
version = "0.1.0"
edition = "2021"[dependencies]
aabbcclib = { path = "../aabbcclib"}

结果:

[root@local_tmp]#
[root@local_tmp]# cargo runCompiling aabbcc v0.1.0 (/home/test/rust/aabbcc)Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.13sRunning `target/debug/aabbcc`
hello word!
[root@local_tmp]# 

编译完成之后,目录结构如下:

[root@local_tmp]# 
[root@local_tmp]# tree aabbcc
aabbcc
├── Cargo.lock
├── Cargo.toml
├── src
│   └── main.rs
└── target├── CACHEDIR.TAG└── debug├── aabbcc├── aabbcc.d├── build├── deps│   ├── aabbcc-49391c9ce0dd82a0.d│   ├── aabbcc-84eb0ba1a4a88edc│   ├── aabbcc-84eb0ba1a4a88edc.d│   ├── aabbcclib-d9564471adb370cd.d│   ├── libaabbcclib-d9564471adb370cd.rlib     【aabbcclib编译出来的依赖文件】│   └── libaabbcclib-d9564471adb370cd.rmeta├── examples└── incremental├── aabbcc-32tbjx4kpc5o5│   ├── s-gwhppxp0pa-1ic334c.lock│   └── s-gwhppxp0pa-1ic334c-working│       └── dep-graph.part.bin├── aabbcc-359ez89eexpbs│   ├── s-gwhpsdi234-1vmcsrh-b7meolpzpay5c7bzdt7fj0aqq│   │   ├── 2d7769k2w2u4ba9i.o│   │   ├── 30oc5b5vjbjp03t3.o│   │   ├── 3327fd3xu1y9eitd.o│   │   ├── 3jd9ttq97rxu8p2.o│   │   ├── dep-graph.bin│   │   ├── mqnstxk6boz9z07.o│   │   ├── query-cache.bin│   │   └── work-products.bin│   └── s-gwhpsdi234-1vmcsrh.lock└── aabbcclib-3a3tgxolnlvpa├── s-gwhps1w5b9-1ahwv4j-6c5oe93zjeabnfxq2te2texnn│   ├── 3u3f9el7ynvgv0eg.o│   ├── dep-graph.bin│   ├── eeyir3875y7wft1.o│   ├── query-cache.bin│   └── work-products.bin└── s-gwhps1w5b9-1ahwv4j.lock13 directories, 29 files
[root@local_tmp]# 
[root@local_tmp]# 
[root@local_tmp]#  tree aabbcclib/
aabbcclib/
├── Cargo.toml
└── src└── lib.rs1 directory, 2 files
[root@local_tmp]# 
[root@local_tmp]# 

7、从键盘输入

        在Rust中,可以使用std::io模块中的stdin来从键盘接收数据。

use std::io;fn main() {println!("请输入一些文本:");let mut input = String::new();io::stdin().read_line(&mut input).expect("无法读取输入");println!("你输入的是:{}", input);
}

结果:

[root@local_tmp]# cargo runCompiling a-1 v0.1.0 (/home/test/rust/a-1)Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.18sRunning `target/debug/a-1`
请输入一些文本:
adasjdahfashfa
你输入的是:adasjdahfashfa

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/diannao/16248.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

栈和队列的基本见解

1.栈 1.1栈的基本概念和结构&#xff1a; 栈是一种特殊的线性表&#xff0c;其只允许在固定的一端进行插入和删除元素操作。进行数据插入和删除操作的一端称为栈顶&#xff0c;另一端称为栈底。栈中的数据元素遵守后进先出的原则。 压栈&#xff1a;栈的插入操作叫做进栈/压栈…

git使用简述

1、工作区、暂存区、版本库 Git 是一个开源的分布式版本控制系统&#xff0c;它允许多个开发者同时在同一个项目上工作&#xff0c;而不会互相干扰。Git 通过三个主要的区域来管理文件的变更&#xff1a;工作区&#xff08;Working Directory&#xff09;、暂存区&#xff08;…

python 面对对象 类 魔法方法

魔法方法 一、__init__ 构造函数&#xff0c;可以理解为初始化 触发条件&#xff1a;在实例化的时候就会触发 class People():def __init__(self, name):print(init被执行)self.name namedef eat(self):print(f{self.name}要吃饭)a People(张三) a.eat() # in…

海外抖音TK自动挂机,手机全自动挂机,每天轻松搞2张

海外抖音TK自动挂机&#xff0c;手机全自动挂机&#xff0c;每天轻松搞2张 课程获取方式&#xff1a; https://zzmbk.com/

整理好了!2024年最常见 20 道 Redis面试题(七)

上一篇地址&#xff1a;整理好了&#xff01;2024年最常见 20 道 Redis面试题&#xff08;六&#xff09;-CSDN博客 十三、如何保证 Redis 的高可用性&#xff1f; Redis&#xff08;Remote Dictionary Server&#xff09;是一个开源的高性能键值对数据库&#xff0c;它通常被…

揭秘Markdown:轻松掌握基础语法,让你的写作更高效、优雅!

文章目录 前言1.标题1.1 使用 和 - 标记一级和二级标题1.2 使用 # 号标记 2.段落格式2.1 字体2.2 分割线2.3 删除线2.4 下划线2.5 脚注 3.列表3.1 无序列表3.2 有序列表3.3 列表嵌套 4.区块4.1 区块中使用列表4.2 列表中使用区块 5.代码代码区块 6.链接7.图片8.表格9.高级技巧…

mysql实战——XtraBackup二进制包安装

1、二进制包下载网站 Software Downloads - Percona 2、安装xtrabackup 解压安装包 tar xvf percona-xtrabackup-8.0.27-19-Linux-x86_64.glibc2.17.tar.gz -C /usr/local 进入目录 cd percona-xtrabackup-8.0.27-19-Linux-x86_64.glibc2.17/ 安装依赖 yum install perl-Dig…

正运动视觉与运动一体机小课堂----三分钟系列

【视觉运控一体机小课堂】三分钟搭建机器视觉开发环境-正运动技术 (zmotion.com.cn) 【视觉运控一体机小课堂】三分钟读取本地图像-正运动技术 (zmotion.com.cn) 【视觉运控一体机小课堂】三分钟实现相机采集和图像保存-正运动技术 (zmotion.com.cn) 【视觉运控一体机小课堂…

java里面反射和动态代理的基础知识

反射 在Java中&#xff0c;反射&#xff08;Reflection&#xff09;是一种强大的工具&#xff0c;它允许程序在运行时检查和修改类、接口、字段和方法等元数据的行为。通过反射&#xff0c;你可以加载类、实例化对象、调用方法、获取和修改字段的值等&#xff0c;而无需在编译…

Fortran: stdlib标准库

Fortran 标准库 stdlib_logger,stdlib_error, stdlib_sorting,stdlib_optval模块挺好用 封装 stdlib_logger和stdlib_error: M_logger.F90 module M_loggeruse stdlib_loggeruse stdlib_error containssubroutine info(message,module,procedure)character(len*),intent(in):…

2024.5.25期末测试总结

成绩&#xff1a; 配置&#xff1a; 可能与实际有些出入 题目&#xff1a; 第一题&#xff1a; 代码思路&#xff1a; 一道模拟题&#xff0c;按照公式计算出sumpow(2,i)&#xff0c;判断sum>H&#xff0c;输出 代码&#xff1a; #include<bits/stdc.h> using name…

Java—内部类

Java—内部类 一、内部类二、应用特点三、分类3.1、普通内部类&#xff1a;直接将一个类的定义放在另外一个类的类体中3.2、静态内部类3.3、局部内部类 一、内部类 一个类的定义出现在另外一个类&#xff0c;那么这个出现的类就叫内部类(Inner)。 内部类所在的类叫做外部类(Ou…

Java匿名内部类的使用

演示匿名内部类的使用&#xff0c;很重要 package com.shedu.Inner;/*** 演示匿名内部类的使用*/ public class AnonymousInnerClass {//外部其他类public static void main(String[] args) {Outer04 outer04 new Outer04();outer04.method();} }class Outer04{//外部类priva…

在线软件包管理

1.APT工作原理 APT&#xff08;Advanced Packaging Tool&#xff09;是Debian系列Linux操作系统中广泛使用的包管理工具&#xff0c;它为用户提供了从软件仓库搜索、安装、升级和卸载软件包的功能。其工作原理具体分析如下&#xff1a; 1. **集中式软件仓库机制**&#xff1a…

Linux之Nginx

1、Nginx 1.1、什么是Nginx Nginx最初由Igor Sysoev开发&#xff0c;最早在2004年公开发布。它被设计为一个轻量级、高性能的服务器&#xff0c;能够处理大量并发连接而不消耗过多的系统资源。Nginx的架构采用了事件驱动的方式&#xff0c;能够高效地处理请求。它的模块化设计使…

python-情报加密副本

【问题描述】某情报机构采用公用电话传递数据&#xff0c;数据是5位的整数&#xff0c;在传递过程中是加密的。加密规则如下&#xff1a;每位数字都加上8,然后用和除以7的余数代替该数字&#xff0c;再将第1位和第5位交换&#xff0c;第2位和第4位交换。请编写程序&#xff0c;…

Denoising Diffusion Probabilistic Models 全过程概述 + 论文总结

标题&#xff1a;Denoising&#xff08;&#x1f31f;去噪&#xff09;Diffusion Probabilistic Models&#xff08;扩散概率模型&#xff09; 论文&#xff08;NeurIPS会议 CCF A 类&#xff09;&#xff1a;Denoising Diffusion Probabilistic Models 源码&#xff1a;hojona…

卡特兰数-

是组合数学中一种常出现于各种计数问题中的数列。 一、简单介绍 卡特兰数是一个数列&#xff0c;其前几项为&#xff08;从第零项开始&#xff09; : 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, 208012, 742900, 2674440, 9694845, 35357670, 129644790, 47763…

QT---JSON使用

一、json 文件概述 JSON(JavaScript 0bject Notation)是一种轻量级的数据交换格式。易于人阅读和编写,可以在多种语言之间进行数据交换。同时也易于机器解析和生成,并有效地提升网络传输效率。采用完全独立于编程语言的文本格式来存储和表示数据。简洁和清晰的层次结构使得 J…

lllyasviel /Fooocus图像生成软件(基于 Gradio)

一、简介 1、Fooocus 是一款图像生成软件(基于 Gradio)。 Fooocus is an image generating software (based on Gradio). Fooocus 是一款图像生成软件(基于 Gradio)。 Fooocus is a rethinking of Stable Diffusion and Midjourney’s designs: Fooocus 是对 Stable Diff…