Rust入门
Rust入门
相关网站
- Rust官网:https://www.rust-lang.org/zh-CN/
- Rust文档网:https://rustwiki.org/
- Rust 官方文档:https://rustwiki.org/zh-CN/
- Rust标准库:https://rustwiki.org/zh-CN/std/
- Rust语言中文社区: https://rustcc.cn/
入门还是看官网基础教程吧~~懒得写了
#[derive(Debug)]
struct User {
id: u8,
name: String,
age: u8,
}
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
// 定义于 Rectangle 结构体上的方法
// 相当于C++中strcut或者class里的方法
// 它们第一个参数总是 self,它代表调用该方法的结构体实例(相当于C++的this指针?)
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
fn can_hold(&self, other: &Rectangle) -> bool {
self.width > other.width && self.height > other.height
}
// 关联函数--C++中的静态成员函数?
// 关联函数经常被用作返回一个结构体新实例的构造函数
fn square(size: u32) -> Rectangle {
Rectangle {
width: size,
height: size,
}
}
}
fn main() {
println!("Hello, world!");
let s1 = " ";
let mut s1 = s1.len();
println!("s1 {}", s1);
xx();
while s1 != 20 {
println!("s1 {}", s1);
s1 = s1 + 1;
}
let s2 = [1, 2, 3, 4, 5, 6];
for t in s2.iter() {
println!("t {}", t);
}
for ele in s2 {
println!("ele {}", ele);
}
let user = User {
id: 1,
name: String::from("dark"),
age: 18,
};
println!("user: {}-{}-{}", user.id, user.name, user.age);
println!("user: {:?}", user);
println!("user: {:#?}", user);
let rect1 = Rectangle {
width: 30,
height: 50,
};
println!(
"The area of the rectangle is {} square pixels.",
rect1.area()
);
let rect1 = Rectangle {
width: 30,
height: 50,
};
let rect2 = Rectangle {
width: 10,
height: 40,
};
let rect3 = Rectangle {
width: 60,
height: 45,
};
println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2));
println!("Can rect1 hold rect3? {}", rect1.can_hold(&rect3));
}
fn xx() {
println!("xxx");
}
更换为国内源
在用户目录下的.cargo目录下,创建一个config文件,添加如下内容
[source.crates-io]
registry = "https://github.com/rust-lang/crates.io-index"
replace-with = 'tuna'
[source.tuna]
registry = "https://mirrors.tuna.tsinghua.edu.cn/git/crates.io-index.git"
[net]
git-fetch-with-cli = true