写一个Rust程序

Rust官网

Rust 程序设计语言 (rust-lang.org)

Rust开发工具

Rustup

在线编译工具

Rust Playground (rust-lang.org)

Hello world

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

第二个重要的部分是 println!() 。这称为 Rust 宏,Rust 元编程(metaprogramming)的关键所在。如果是调用函数,则应看起来像这样: println (没有 ! )。现在你只需记住,当看到符号 ! 的时候,就意味着调用的是宏而不是普通函数。

Rust学有所感

1、《Rust 程序设计语言(第二版)》整体(粗略)看完,Rust语言学习难度对比现有编程语言(对比C、C++、C#、Python、Java、PHP、HTML、shell等)复杂程度相对偏高。从Rust官网获取的第一份代码应该是某Rust库源码片段,第一感受像是在读“汇编”。Rust语言难度大主要是两方面因素,一是语法有点反人类,二是基于安全特性和性能的平衡,引入的一些新概念、新理论。
2、很期待Rust2.0,一门能兼顾C的效率于Java的安全性的语言,一定是程序员需要的语言。
3、Rust学习资料官网整理得很齐全,工具、资料都不错,如果没有官网整理的学习资料,Rust语言一定劝退不少人。
4、Rust语言有一些新的理念,新的限制或平衡,重要的是已经付诸实施,值得学习。
5、《Rust 程序设计语言(第二版)》中对关键字、运算符、宏和可导出的 trait没有归纳总结,现在编写程序对语法基本没有依赖,相反去读懂程序是一定要懂语法。

关键字

项目关键字含义解析
1as用于进行类型转换
2break用于中断循环或跳转到标签处
3const声明一个常量
4continue跳过当前迭代并开始下一次迭代
5crate表示一个模块单元的根
6dyn用于动态分发和实现Trait对象
7else与if条件不满足时执行的代码块
8enum定义一个枚举类型
9extern用于引入外部库或函数
10false布尔类型的假值
11fn定义一个函数或方法
12for用于遍历集合或范围
13if用于条件判断
14impl用于为类型实现方法和Trait
15in在for循环中用于指定迭代器
16let用于声明变量
17loop无限循环,直到遇到break语句
18match用于模式匹配和多路分支
19mod定义一个模块
20move用于强制获取变量的所有权
21mut可变绑定修饰符
22pub公共可见性修饰符
23ref创建引用绑定
24return从函数或闭包中返回
25Self表示当前类型
26self表示当前实例或模块
27static声明一个静态变量
28struct定义一个结构体类型
29super表示父模块或父结构体
30trait定义一个Trait(特性)
31true布尔类型的真值
32type定义一个类型别名
33unsafe标记不安全的代码块
34use用于导入路径、模块或符号
35where在泛型约束中使用的关键字
36while循环执行指定的代码块,直到条件不满足

as

用于进行类型转换。

let x: i32 = 5;
let y = x as f64; // 将x转换为f64类型

break

用于中断循环或跳转到标签处。

for i in 0..10 {
    if i == 5 {
        break; // 中断循环
    }
    println!("{}", i);
}
const
声明一个常量。
const MAX_VALUE: u32 = 100; // 声明一个名为MAX_VALUE的常量,值为100
continue
跳过当前迭代并开始下一次迭代。
for i in 0..5 {
    if i % 2 == 0 {
        continue; // 跳过偶数,并开始下一次迭代
    }
    println!("{}", i);
}

crate

表示一个模块单元的根。

mod my_module {
    pub fn hello() {
        println!("Hello from my_module!");
    }
}

use crate::my_module::hello; // 使用crate关键字引用上级模块

fn main() {
    hello(); // 调用my_module模块中的hello函数
}

dyn

用于动态分发和实现Trait对象。

trait MyTrait {
    fn print(&self);
}

struct MyStruct;

impl MyTrait for MyStruct {
    fn print(&self) {
        println!("This is MyStruct");
    }
}

fn main() {
    let obj: Box<dyn MyTrait> = Box::new(MyStruct);
    obj.print();
}

else

与if条件不满足时执行的代码块。

let x = 5;

if x > 10 {
    println!("x is greater than 10");
} else {
    println!("x is less than or equal to 10");
}
enum
定义一个枚举类型。
enum Color {
    Red,
    Green,
    Blue,
}

let c: Color = Color::Red;

extern

用于引入外部库或函数。

extern crate rand; // 引入外部库

fn main() {
    println!("Random number: {}", rand::random::<u32>());
}

false

布尔类型的假值。

let is_true = true;
let is_false = false;

if is_true {
    println!("It's true!");
} else if is_false {
    println!("It's false!"); // 不会执行到这里
} else {
    println!("Neither true nor false");
}

fn

定义一个函数或方法。

fn add(a: i32, b: i32) -> i32 {
    return a + b;
}

let result = add(5, 3);
println!("The result is: {}", result);

for

用于遍历集合或范围。

let numbers = vec![1, 2, 3, 4, 5];

for num in numbers {
    println!("{}", num);
}

if

用于条件判断。

let x = 10;

if x > 5 {
    println!("x is greater than 5");
} else if x < 5 {
    println!("x is less than 5"); // 不会执行到这里
} else {
    println!("x is equal to 5");
}

impl

用于为类型实现方法和Trait。

struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    fn area(&self) -> u32 {
        self.width * self.height
    }
}

let rect = Rectangle { width: 10, height: 20 };
println!("Area: {}", rect.area());

in

在for循环中用于指定迭代器。

let numbers = vec![1, 2, 3, 4, 5];

for num in &numbers {
    println!("{}", num);
}

let

用于声明变量。

let x = 10;
let y: i32 = 20;

let sum = x + y;
println!("The sum is: {}", sum);

loop

无限循环,直到遇到break语句。

let mut count = 0;

loop {
    println!("Count: {}", count);
    count += 1;

    if count == 5 {
        break;
    }
}

match

用于模式匹配和多路分支。

let number = 5;

match number {
    1 => println!("One"),
    2 => println!("Two"),
    3 | 4 => println!("Three or Four"),
    _ => println!("Other"), // 匹配其它情况
}

mod

定义一个模块。

mod my_module {
    pub fn hello() {
        println!("Hello from my_module!");
    }
}

use crate::my_module::hello;

fn main() {
    hello();
}

move

用于强制获取变量的所有权。

fn main() {
    let name = String::from("Alice");

    std::thread::spawn(move || {
        println!("Hello, {}!", name);
    }).join().unwrap();
}

mut

可变绑定修饰符。

let mut count = 0;
count += 1;
println!("Count: {}", count);
pub
公共可见性修饰符。
pub const MAX_VALUE: u32 = 100;

pub fn add(a: i32, b: i32) -> i32 {
    return a + b;
}

ref

创建引用绑定。

let value = 42;
let reference = &value;

match reference {
    &ref val => println!("Value: {}", val),
}

return

从函数或闭包中返回。

fn add(a: i32, b: i32) -> i32 {
    return a + b;
}

let result = add(5, 3);
println!("The result is: {}", result);

Self

表示当前类型。

struct Point {
    x: i32,
    y: i32,
}

impl Point {
    fn new(x: i32, y: i32) -> Self {
        Self { x, y }
    }
}

let point = Point::new(1, 2);
println!("Point: ({}, {})", point.x, point.y);

self

表示当前实例或模块。

struct Circle {
    radius: f64,
}

impl Circle {
    fn area(&self) -> f64 {
        std::f64::consts::PI * self.radius * self.radius
    }
}

let circle = Circle { radius: 5.0 };
println!("Area: {}", circle.area());

static

声明一个静态变量。

static MAX_VALUE: u32 = 100;

fn main() {
    println!("Max Value: {}", MAX_VALUE);
}

struct

定义一个结构体类型。

struct Person {
    name: String,
    age: u32,
}

let person = Person {
    name: String::from("Alice"),
    age: 25,
};
println!("Name: {}, Age: {}", person.name, person.age);

super

表示父模块或父结构体。

mod outer_module {
    pub mod inner_module {
        pub fn hello() {
            println!("Hello from inner_module!");
        }
    }
}

use crate::outer_module::inner_module::hello;

fn main() {
    hello();
}

trait

定义一个Trait(特性)。

trait Printable {
    fn print(&self);
}

struct Person {
    name: String,
    age: u32,
}

impl Printable for Person {
    fn print(&self) {
        println!("Name: {}, Age: {}", self.name, self.age);
    }
}

let person = Person {
    name: String::from("Alice"),
    age: 25,
};

person.print();

true

布尔类型的真值。

let is_true = true;

if is_true {
    println!("It's true!");
} else {
    println!("It's false!"); // 不会执行到这里
}

type

定义一个类型别名。

type Distance = f64;

fn calculate_distance(x1: f64, y1: f64, x2: f64, y2: f64) -> Distance {
    ((x2 - x1).powi(2) + (y2 - y1).powi(2)).sqrt()
}

let distance = calculate_distance(0.0, 0.0, 3.0, 4.0);
println!("Distance: {}", distance);

unsafe

标记不安全的代码块。

unsafe fn dangerous_function() {
    // 执行不安全的操作
}

unsafe {
    dangerous_function();
}

use

用于导入路径、模块或符号。

use std::io::{self, Write};

fn main() {
    io::stdout().write(b"Hello, World!").unwrap();
}

where

在泛型约束中使用的关键字。

fn process<T>(value: T)
where
    T: Display + Clone,
{
    println!("{}", value);
}

process("Hello, World!");

while

循环执行指定的代码块,直到条件不满足。

let mut count = 0;

while count < 5 {
    println!("Count: {}", count);
    count += 1;
}

运算符与符号

算术运算符

  • +:加法
  • -:减法
  • *:乘法
  • /:除法
  • %:取模(余数)
  • +=:加法赋值
  • -=:减法赋值
  • *=:乘法赋值
  • /=:除法赋值
  • %=:取模赋值

关系运算符

  • ==:相等
  • !=:不等
  • <:小于
  • >:大于
  • <=:小于等于
  • >=:大于等于

逻辑运算符

  • &&:逻辑与
  • ||:逻辑或
  • !:逻辑非

位运算符

  • &:按位与
  • |:按位或
  • ^:按位异或
  • <<:左移
  • >>:右移
  • &=:按位与赋值
  • |=:按位或赋值
  • ^=:按位异或赋值
  • <<=:左移赋值
  • >>=:右移赋值

赋值运算符

  • =:赋值

其他运算符与符号

  • .:成员访问符
  • ..:范围运算符
  • ():函数调用符
  • []:索引访问符
  • ::类型标注
  • ;:语句结束符
  • ,:逗号分隔符

println

println!:用于格式化输出到标准输出。

let name = "Alice";
let age = 25;

println!("My name is {} and I am {} years old.", name, age);

format

format!:用于格式化字符串,返回一个新的String

let name = "Bob";
let age = 30;

let message = format!("My name is {} and I am {} years old.", name, age);
println!("{}", message);

assert

assert!:用于断言条件是否为真,如果条件为假,则触发断言失败。

fn add(a: i32, b: i32) -> i32 {
    assert!(a >= 0, "a must be non-negative");
    assert!(b >= 0, "b must be non-negative");

    return a + b;
}

let result = add(5, -3); // 会触发断言失败,程序会终止并打印错误信息
println!("The result is: {}", result);

vec

vec!:用于创建动态数组(Vec)。

let numbers = vec![1, 2, 3, 4, 5];
println!("{:?}", numbers);

include_str

include_str!:将文件内容作为字符串包含。

let contents = include_str!("file.txt");
println!("File contents:\n{}", contents);

可导出的 trait

在Rust语言中,trait是一种用于定义共享行为的机制。

Clone

Clone:用于支持对象的克隆和复制。

pub trait Clone {
    fn clone(&self) -> Self;
    fn clone_from(&mut self, source: &Self) {
        // 默认实现
    }
}

Copy

Copy:用于支持对象的简单复制。

pub trait Copy: Clone {}
Default
`Default`:用于提供类型的默认值。
pub trait Default {
    fn default() -> Self;
}

Eq和PartialEq

EqPartialEq:用于比较相等性。

pub trait PartialEq<Rhs = Self>: Eq<Rhs> {
    fn eq(&self, other: &Rhs) -> bool;

    fn ne(&self, other: &Rhs) -> bool {
        !self.eq(other)
    }
}

pub trait Eq: PartialEq<Self> {}

Ord和PartialOrd

OrdPartialOrd:用于比较大小。

pub trait PartialOrd<Rhs = Self>: PartialEq<Rhs> {
    fn partial_cmp(&self, other: &Rhs) -> Option<Ordering>;

    fn lt(&self, other: &Rhs) -> bool;
    fn le(&self, other: &Rhs) -> bool;
    fn gt(&self, other: &Rhs) -> bool;
    fn ge(&self, other: &Rhs) -> bool;
}

pub trait Ord: Eq + PartialOrd<Self> {}

Iterator

Iterator:用于创建迭代器。

pub trait Iterator {
    type Item;

    fn next(&mut self) -> Option<Self::Item>;

    // 其他方法...
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值