一、常量
Rust | Javascript |
---|---|
let | const |
二、变量
Rust | Javascript |
---|---|
let mut | let / var |
三、常用打印
Rust | Javascript |
---|---|
println!(“换行”); | console.log(‘hello’); |
print!(“不换行”); | console.info(‘信息’); |
- | console.error(‘错误’); |
- | console.warn(‘警告’); |
四、定义字符串
Rust | Javascript |
---|---|
let a = String::from(“xxx”); | let a = “xxx”; |
五、定义类json
Rust
fn main() {
let user: User = User {
username: String::from("Tom"),
email: String::from("XXX@qq.com"),
sign_in_count: 9,
active: true
};
println!("{:?}", user);
println!("{}", user.username);
println!("{}", user.email);
println!("{}", user.sign_in_count);
println!("{}", user.active);
}
// `#[derive(Debug)]` 是 Rust 中的一个属性(attribute),用于自动生成实现 `Debug` trait 的代码。该属性可以应用于结构体、枚举和联合体等类型。
#[derive(Debug)]
struct User {
username: String,
email: String,
sign_in_count: u64,
active: bool
}
Javascript
const user = {
username: "Tom",
email: "XXX@qq.com",
sign_in_count: 9,
active: true
}
console.log(user)
六、循环中的break
Rust
fn main() {
let arr: [&str; 5] = ["L", "C", "W", "A", "I"];
let mut i = 0;
let lo = loop {
let w = arr[i];
if w == "W" {
break i;
}
i += 1;
};
println!("{}", lo);
}
Javascript
const arr = ["L", "C", "W", "A", "I"];
let lo = 0
for (let i=0; i < arr.length; i += 1) {
let w = arr[i];
if (w == "W") {
lo = i
break
}
};
console.log(lo)
七、条件语句
Rust 中的条件表达式必须是 bool 类型,否则报错
正确的如下
fn main() {
let a = 10;
if a > 0 {
println!("a is more than 0")
}
}
Javascript中的条件表达式则没那么严格
const a = 10
if (a) {
console.log("a is true")
}
后面待续