Win10/11系统Rust安装 + WebAssembly入门实战(从0到1超详细)

1 Windows下安装Rust

1、Windows系统,先到官网下载安装Rustup(内含Cargo,即Rust 的构建工具和包管理器)

https://www.rust-lang.org/zh-CN/learn/get-started

​ 注意:在Windows上,安装Rust前,会提示先安装依赖的Microsoft C++构建工具,下载地址

https://visualstudio.microsoft.com/zh-hans/visual-cpp-build-tools/

下载下来之后,居然是一个Visual Studio Installer的集成安装工具,为了节省空间,只需要勾选C++生成工具,另外语言包至少勾选"英语"。安装后总共占用5个多G的存储空间。注意选择安装位置,否则默认安装到C盘**。

MS C++安装

安装完成之后需要重启电脑。

如果不安装的话,直接cargo run会有如下提示:

PS D:\dev\rust\hello-world> cargo run
   Compiling hello-world v0.1.0 (D:\dev\rust\hello-world)
error: linker `link.exe` not found
  |
  = note: program not found

note: the msvc targets depend on the msvc linker but `link.exe` was not found

note: please ensure that VS 2013, VS 2015, VS 2017, VS 2019 or VS 2022 was installed with the Visual C++ option

error: could not compile `hello-world` due to previous error

MSVC++构建工具安装完成之后,直接运行rustup-init.exe,耐心等待Rust安装完成。

Current installation options:

   default host triple: x86_64-pc-windows-msvc
     default toolchain: stable (default)
               profile: default
  modify PATH variable: yes

1) Proceed with installation (default)
2) Customize installation
3) Cancel installation
>1 #选1,典型安装即可
#...耐心等待下载安装
  stable installed - rustc 1.44.1 (c7087fe00 2020-06-17)

Rust is installed now. Great!

重新打开一个命令行,输入

> cargo -V
cargo 1.44.1 (88ba85757 2020-06-11)
> rustc -V
rustc 1.44.1 (c7087fe00 2020-06-17)

检查Rust是否安装成功。

2 Rust Hello World

进入某个目录,如D:/dev/rust,执行cargo new hello-world创建一个rust项目。

rust项目名称习惯用短横线进行单词分隔,而rust变量名、函数名习惯用短下划线进行分隔。

cargo new hello-world
     Created binary (application) `hello-world` package
cd ./hello-world
cargo run #编译运行
   Compiling hello-world v0.1.0 (D:\dev\rust\hello-world)
    Finished dev [unoptimized + debuginfo] target(s) in 0.89s
     Running `target\debug\hello-world.exe`
Hello, world!

采坑备注

​ 可能会遇到的问题:

​ 如果项目中引入了其他crate(Rust的代码发布包),使用默认官方的仓库,因为网络原因很可能会一直Blocking...

​ 解决办法:

​ 1、 删掉{安装目录}/.cargo/.package-cache文件。否则会一直Blocking…
安装目录默认为:C:/Users/用户名

​ 2、 最好是替换掉官方的仓库为国内的镜像地址(俗称换源)。

  • 在C:/Users/admin/.cargo/目录下新建一个config文件,填入如下内容:

    [source.crates-io]
    replace-with = "gitee"
     
    [source.gitee]
    registry = "https://gitee.com/Aloxaf/crates.io-index"
    

    这是笔者在gitee找到的一个可以正常使用的镜像,不过可能更新不及时。

    还是建议换成中科大的:

    [source.crates-io]
    replace-with = 'ustc'
    [source.ustc]
    registry = "https://mirrors.ustc.edu.cn/crates.io-index"
    [http]
    check-revoke = false
    

    如果不行,还是可以试试清华大学的镜像

    [source.crates-io]
    replace-with = 'tuna'
    
    [source.tuna]
    registry = "https://mirrors.tuna.tsinghua.edu.cn/git/crates.io-index"
    

3 rustup 更新

如果编译中报错:

error[E0658]: `while` is not allowed in a `const fn`

可能是rustup和rust工具链太老了,执行rustup update进行升级。

4 crates搬家:指定CARGO_HOME

rust默认会被安装在C:/users/xxx/.cargo目录下。
可以将安装目录迁移到其他盘符下面,然后添加CARGO_HOME环境变量指向该目录即可。
比如,笔者将CARGO_HOME环境变量设置为:E:\env\rust.cargo

5 VSCode Rust插件(强烈推荐)

可以用VSCode打开,刚刚cargo命令创建的hello-world目录。
强烈推荐如下几个插件:
1,rust-analyzer:它会实时编译和分析你的 Rust 代码,提示代码中的错误,并对类型进行标注。比官方的 rust 插件好用。(两者有冲突,需要禁用另外一个)
2,rust syntax:rust代码语法高亮。
3,crates:检查所依赖的第三方包是否是最新的版本,列出可用的版本。
4,better toml,Toml 配置文件高亮显示,并检查 toml 文件中的错误。
5,rust test lens:可以帮你快速运行某个 Rust 测试。
6,Tabnine:基于 AI 的智能自动补全,高效写代码“神器”。

6 Rust + WebAssembly上手初探

  1. Rust官方对WebAssembly有很好的支持。

cargo-generate 用于快速生成 WASM 项目的脚手架(类似 create-react-app),运行 cargo install cargo-generate开始安装。

cargo install cargo-generate
  1. wasm-pack 用于将 Rust 项目打包成单个 WASM 文件(类似 Webpack),下载地址:

https://rustwasm.github.io/wasm-pack/installer/

下载windows的,直接运行wasm-pack-init.exe安装。

info: successfully installed wasm-pack to `C:\Users\liny\.cargo\bin\wasm-pack.exe`
Press enter to close this window...
  1. 创建一个WASM项目:
cargo generate --git https://github.com/rustwasm/wasm-pack-template

在项目目录下运行wasm-pack build命令,即可编译出 WASM 模块。wasm-pack会在项目的pkg目录下生成 .wasm等文件。

备注:

  1. 可能国内镜像仓库里面缺少一些依赖包的最新版本,导致wasm-pack-template无法build成功,可尝试降低Cargo.toml中依赖项的版本。

  2. build之后会提示[INFO]: Installing wasm-bindgen...这个过程首次可能比较长,笔者等了7分多钟,终于还是完成了。

build成功之后,在pkg目录下生成.wasm文件和相关的js胶水代码。

有点前端基础的同学接下来就知道怎么把.wasm引入前端项目了吧。

6 不用Webpack打包前端代码,直接浏览器访问

上面wasm-pack build生成的代码是Webpack项目的,需要webpack打包成原生js才能跑在浏览器当中。

不过,对于一些简单的前端项目和一些测试代码,笔者喜欢干净、原生的js直接丢浏览器跑。

如此操作一番:

  1. 带参数重新build,生成可以在浏览器跑的js代码
wasm-pack build --target browser 
  1. 自己写一个XHR,从服务器端读取xxx.wasm文件。

    function getAsm(options) {
        options = options || {};
        options.type = (options.type || "GET").toUpperCase();
        options.dataType = options.dataType || "json";
        var params;
    
        var xhr = new XMLHttpRequest();
        xhr.responseType = 'arraybuffer';
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4) {
                var status = xhr.status;
                if((status >= 200 && status < 300) || status == 304) {
                    options.success && options.success(xhr.response);
                } else {
                    options.error && options.error(status);
                }
            }
        };
        xhr.open("GET", options.url, true);
    };
    
    //把build出来的js胶水代码拷贝到这里
    
    
    var imports = {};//这里放需要导入到rust,让rust调用的函数
    getAsm({
        url: 'xxx_bg.wasm',
        success: function(data) {
            var result = WebAssembly.instantiate(data, imports);
            result.then(function(data) {
                //这里就获取到wasm导出的函数
                //后续就可以通过wasm.xxxFunc()调用Rust代码编译出来的函数了
                window.wasm = data.instance.exports;
            })
        }
    });
    

    踩坑备注:

    观察js胶水代码中对TextDecoder的初始化:

    let cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });
    

    ignoreBOM参数默认是true,实际上笔者在IPhone和Android机上测试,ignoreBOM为true时,从wasm模块得到的string居然是带BOM的!!(不应该是为true会忽略BOM么?这语义有Bug啊!

    ignoreBOM改为传入false,就OK了。

    这个问题,笔者在另一篇文章有详细说明:WebAssembly+Rust:wasm返回给js的字符串长度看似不对的问题

全文完。

  • 5
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值