Rust与Javascript的使用对比

一、常量

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("[email protected]"),
        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: "[email protected]",
    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")
}

后面待续

相关推荐
沐土Arvin1 小时前
理解npm的工作原理:优化你的项目依赖管理流程
开发语言·前端·javascript·设计模式·npm·node.js
好_快1 小时前
Lodash源码阅读-baseUniq
前端·javascript·源码阅读
牧羊狼的狼1 小时前
React.memo 和 useMemo
前端·javascript·react.js
好_快2 小时前
Lodash源码阅读-uniq
前端·javascript·源码阅读
梦境之冢3 小时前
在 Vue3 中封装的 Axios 实例中,若需要为部分接口提供手动取消请求的功能
javascript·vue.js
qq_456001654 小时前
在Vue3中,如何在父组件中使用v-model与子组件进行双向绑定?
前端·javascript·vue.js
一夜枫林7 小时前
uniapp自定义拖拽排列
前端·javascript·uni-app
YiSLWLL8 小时前
使用Tauri 2.3.1+Leptos 0.7.8开发桌面小程序汇总
python·rust·sqlite·matplotlib·visual studio code
yu4106218 小时前
Rust 语言使用场景分析
开发语言·后端·rust
良艺呐^O^8 小时前
uniapp实现app自动更新
开发语言·javascript·uni-app