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("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")
}

后面待续

相关推荐
guyoung1 分钟前
BoxAgnts 工具系统(7)——Skill 模板、Agent 代理与 Cron 调度
rust·agent·ai编程
丷丩1 小时前
MapLibre GL JS第47课:添加动画图标
javascript·gis·动画·mapbox·maplibre
快乐的哈士奇2 小时前
【Next.js实战①】Gmail API 按柜号检索邮件:OAuth 双 Cookie 与搜索 Fallback
开发语言·javascript·ecmascript
云水一下2 小时前
Vue.js从零到精通系列(五):全局状态管理——Pinia 核心与实践
前端·javascript·vue.js
分布式存储与RustFS2 小时前
基于Rust的国产开源对象存储RustFS:S3 Table对Iceberg数据湖的适配详解
rust·开源·iceberg·对象存储·rustfs·minio平替·s3 table
kmblack12 小时前
javascript计算年龄
开发语言·javascript·ecmascript
Dick5073 小时前
ROS2 多机器人通用 Driver 层复盘:BaseRobotDriver 到多平台 Mock 切换实现
前端·javascript·机器人
黄敬峰4 小时前
从 XMLHttpRequest 到 JSON 模拟:打通前后端通信的任督二脉
javascript
weixin_471383034 小时前
Taro-03-页面生命周期
前端·javascript·taro