Rust开发笔记

RUST

Rust Tools

cargo

rustfmt

initial rust project

cargo new demo1

cargo build

cargo run

rustfmt main.rs

rust安装

https://www.rust-lang.org/tools/install

http://go-edu.cn/2022/06/05/14-rust-循环

helloWorld

fn main(){
    println!("Hello Rust!")
}
rustc hello.rs
./hello

xx! 宏

println! 宏,输出到标准输出设备

配置 PATH 环境变量

在 Rust 开发环境中,所有工具都安装在 ~/.cargo/bin 目录中,您可以在这里找到包括 rustccargorustup 在内的 Rust 工具链。

C:\Users\Administrator>rustc --version
rustc 1.67.1 (d5a82bbd2 2023-02-07)

C:\Users\Administrator>

C:\Users\Administrator\.cargo\bin>ls -l
total 126932
-rwxr-xr-x 13 Administrator None 9996288 Feb 21 08:31 cargo-clippy.exe
-rwxr-xr-x 13 Administrator None 9996288 Feb 21 08:31 cargo-fmt.exe
-rwxr-xr-x 13 Administrator None 9996288 Feb 21 08:31 cargo-miri.exe
-rwxr-xr-x 13 Administrator None 9996288 Feb 21 08:31 cargo.exe
-rwxr-xr-x 13 Administrator None 9996288 Feb 21 08:31 clippy-driver.exe
-rwxr-xr-x 13 Administrator None 9996288 Feb 21 08:31 rls.exe
-rwxr-xr-x 13 Administrator None 9996288 Feb 21 08:31 rust-gdb.exe
-rwxr-xr-x 13 Administrator None 9996288 Feb 21 08:31 rust-gdbgui.exe
-rwxr-xr-x 13 Administrator None 9996288 Feb 21 08:31 rust-lldb.exe
-rwxr-xr-x 13 Administrator None 9996288 Feb 21 08:31 rustc.exe
-rwxr-xr-x 13 Administrator None 9996288 Feb 21 08:31 rustdoc.exe
-rwxr-xr-x 13 Administrator None 9996288 Feb 21 08:31 rustfmt.exe
-rwxr-xr-x 13 Administrator None 9996288 Feb 21 08:31 rustup.exe

C:\Users\Administrator\.cargo\bin>pwd
/c/Users/Administrator/.cargo/bin

C:\Users\Administrator\.cargo\bin>echo ~/.cargo/bin
~/.cargo/bin

C:\Users\Administrator\.cargo\bin>

PS D:\work\rustpj\hello_world> cargo --version
cargo 1.67.1 (8ecd4f20a 2023-01-10)
PS D:\work\rustpj\hello_world>
PS D:\work\rustpj\hello_world> cargo --version
cargo 1.67.1 (8ecd4f20a 2023-01-10)
PS D:\work\rustpj\hello_world> cd ..
PS D:\work\rustpj> cargo new hello_cargo
     Created binary (application) `hello_cargo` package
PS D:\work\rustpj> cd .\hello_cargo\
PS D:\work\rustpj\hello_cargo>

PS D:\work\rustpj\hello_cargo\src> type .\main.rs
fn main() {
    println!("Hello, world!");
}
PS D:\work\rustpj\hello_cargo\src> cd..
PS D:\work\rustpj\hello_cargo> cargo build
   Compiling hello_cargo v0.1.0 (D:\work\rustpj\hello_cargo)
    Finished dev [unoptimized + debuginfo] target(s) in 0.37s
PS D:\work\rustpj\hello_cargo> dir
目录: D:\work\rustpj\hello_cargo
Mode                 LastWriteTime         Length Name

----                 -------------         ------ ----

d-----         2023/2/21      8:42                src
d-----         2023/2/21      8:44                target
-a----         2023/2/21      8:42              8 .gitignore
-a----         2023/2/21      8:44            155 Cargo.lock
-a----         2023/2/21      8:42            180 Cargo.toml

PS D:\work\rustpj\hello_cargo> cd .\target\
PS D:\work\rustpj\hello_cargo\target> dir

目录: D:\work\rustpj\hello_cargo\target

Mode LastWriteTime Length Name

—- ————- —— —-

d—– 2023/2/21 8:44 debug
-a—- 2023/2/21 8:44 1151 .rustc_info.json
-a—- 2023/2/21 8:44 177 CACHEDIR.TAG

PS D:\work\rustpj\hello_cargo\target> cd .\debug\
PS D:\work\rustpj\hello_cargo\target\debug> dir

目录: D:\work\rustpj\hello_cargo\target\debug

Mode LastWriteTime Length Name

—- ————- —— —-

d—– 2023/2/21 8:44 .fingerprint
d—– 2023/2/21 8:44 build
d—– 2023/2/21 8:44 deps
d—– 2023/2/21 8:44 examples
d—– 2023/2/21 8:44 incremental
-a—- 2023/2/21 8:44 0 .cargo-lock
-a—- 2023/2/21 8:44 96 hello_cargo.d
-a—- 2023/2/21 8:44 162816 hello_cargo.exe
-a—- 2023/2/21 8:44 1298432 hello_cargo.pdb

PS D:\work\rustpj\hello_cargo\target\debug> ./hello_cargo.exe
Hello, world!
PS D:\work\rustpj\hello_cargo\target\debug>

doc.rust-lang.org/std/

https://github.com/daedreth/UncleDavesEmacs/blob/master/init.el

http://wiki.archlinus.org/title/rust#Installation

rustup default stable

rustup toolchain install toolchain

rustup default toolchain

cargo install rust-analyzer

larkin@larkindeMac rust01 % cargo install rust-analyzer
Updating crates.io index
error: there is nothing to install in rust-analyzer v0.0.1, because it has no binaries
cargo install is only for installing programs, and can’t be used with libraries.
To use a library crate, add it as a dependency in a Cargo project instead.
larkin@larkindeMac rust01 % history

https://blog.csdn.net/taoxianchong/article/details/80182809

rust 非emacs包
cargo 非emacs包
rust-mode M-x package-install rust-mode
cargo M-x package-install cargo
racer 非emacs包

emacs –insecure

Installation

Melpa

The package is available on MELPA. Add this to your init.el.

(require 'package)
(add-to-list 'package-archives
             '("melpa" . "https://melpa.org/packages/") t)
(package-initialize)
(package-refresh-contents)

Now you can install rust-mode with:

M-x package-install rust-mode

And put this in your config to load rust-mode automatically:

(require 'rust-mode)

EMACS WITH RUST

rustup default stable

rustup toolchain install toolchain

rustup default toolchain

cargo install rust-analyzer

larkin@larkindeMac rust01 % cargo install rust-analyzer
Updating crates.io index
error: there is nothing to install in rust-analyzer v0.0.1, because it has no binaries
cargo install is only for installing programs, and can’t be used with libraries.
To use a library crate, add it as a dependency in a Cargo project instead.
larkin@larkindeMac rust01 % history

MAC OS

brew install rust-analyzer

M-x lsp restart
M-x lsp diagn

  1. 通过 homebrew 安装 llvm 和 cmake
  2. 检出 lldb-mi 代码库
  3. 构建 lldb-mi 可执行文件
  4. 将目录链接到我的 PATH

快速开始

如果你已经安装了 Rust 和 Emacs 那可以直接快速开始而不用对现有配置做任何修改。可以使用如下命令在启动 Emacs 时加载rksm/emacs-rust-config github 仓库standalone.el 配置文件:

git clone https://github.com/rksm/emacs-rust-config
emacs -q --load ./emacs-rust-config/standalone.el
$ brew install cmake llvm
$ git clone https://github.com/lldb-tools/lldb-mi
$ mkdir -p lldb-mi/build
$ cd lldb-mi/build
$ cmake ..
$ cmake --build .
$ ln -s $PWD/src/lldb-mi /usr/local/bin/lldb-mi

Manually

Add which-key.el to your load-path and require. Something like

(add-to-list 'load-path "path/to/which-key.el")
(require 'which-key)
(which-key-mode)

http://programmingexpert.io/tim

Some,Option

Rust中的关键字Some、Option
根据Rust本身的设计哲学, 建议在设计某个变量时, 如果预计该变量某时刻可能会是空值(null/None)的话, 那么尽量用Option/Result来包裹它, 反过来说, 只有你可以肯定该变量不可能为空值时, 才无须这么搞.

rust为了处理情况设置的两个枚举类型,分别是enum Option 和enum Result。

Option的枚举情况有两种,分别是代表有的Some()和代表无的None。 如果是有返回值,则可以通过if let,match,unwrap,?等多种方法对应情况取出Some包裹的值,如果没有则是None。

Result的枚举情况也是有两种,表示正确的Ok()和表示错误的Err()。同样也是match,unwrap等等对应方法去提取。分别提取对应情况的内容。

创建rust项目 wasm

cargo new –lib hello-wasm

cargo check

Rust

安装wasm-pack

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

rust web 项目

std:tcp

cargo new s1 && cd s1

cargo new tcpserver

cargo new tcpclient

code .

vi carto.toml

[workspace]

members = [“tcpserver”,”tcpclient”]

vi tcpserver/src/main.rs

use std::net::TcpListener;

fn main(){
    let listener = TclListener::bind("127.0.0.1:3000").unwrap();
    println!("Running on port 30000");

    for stream in lintener.incoming(){
        let _stream = stream.unwrap();
        pringln!("Connect established!");
    }
}

cd s1

cargo run -p tcpserver

vi tcpclient/main.rs

use std::net::TcpStream;

fn main() {

let _stream = TcpStream::connect(“localhost:3000”).unwrap();

}

cd s1

cargo run -p tcpclient

构建Http Server(Web Server)

rust 没有内置 http 支持

Web Server

Server

Router

Hander

HTTP Library

cd s1

cargo new httpserver

cargo new –lib http

​ [workspace]

vi Cargo.toml

members = [“tcpserver”,”tcpclient”,”http”,”httpserver”]

cargo build

cargo test -p http

crate

actix

cargo new ws

cd ws

cargo new webservice

actix-web = “3”

actix-rt = “1.1.1”

[[bin]]

name=”server1″

切片

[start..end] 左闭右开

mut 可变

struct 结构体

元组结构体

struct Pair(String, i32)

C语言风格结构体

struct 结构体名称{

}

..

集合

vector

let mut v = Vec::new()
v.push("aa");
v.push("bb")
println!("len:{}",v.len());
let x = v.remove(0);
if v.contains(&"aa"){

}
for item in v{

}

HashMap

let mut process=HashMap:new();
process.insert("aa");
process.insert("bb")
println!("len:",process.len());
match process.get(&"aa"){  
    Some(v)=>{
        println!("HasnMap v:{}",v)   
    }
    None=>{
        println!("can not find!")
    }
}

for (k,v) in process.iter(){
    println!("k:{} v:{}",k,v);
}
if process.contains_key(&"aa"){

}

HashSet

let mut set = HashSet::new();
set.insert("aa");
set.insert("bb");
set.insert("aa");
for item in set.iter(){
    println!("{}",item);
}
match set.get("aa"){
    Some(v)=>{
        println!("find {}",v)
    }
    None=>{
        println!("not find!");
    }
}

Trait 特质,对标其他语言的接口

trait som_trait{

}

impl for ..

|| 闭包

||代替()将参数括起来

|参数列表|{

业务逻辑

闭包可以

引用 &T

可变引用 &mut T

值  T

闭包不用申明返回值,

闭包也称为内联函数, 也叫lambda表达式或者lambda.

线程

fn main(){

    let handler = thread::spawn(||{
    for i in 1..10{
        println!("child thread{}",i);
                            thread::sleep(Duration::from_millis(1));
            }
    })
    for i in 1..5{
        println!("main thread{}",i);
        thread::sleep(Duation::from_millis(1));
    }
    handler.join().unwrap();

}

错误处理

panic!(“Error”);

Recoverable

UnRecoverable

智能指针

如果一个结构体,实现了deref和drop的

trait.

let a = 6;
let b = Box::new(a);
println!("b={}",b);

模块(Module)

mod module_name{

}

多线程

https://crates.io/crates/async-std

use async_std::task

[dependices]

async-std={version = “1.12.0”, features =[“attributes”]}

#[aync_std::]

Rust实战

技术栈:

Rust

PostgresSQL

Diesel

Actix

actix-web=”3.0″

actix-rt=”1.0″

chrono={vesion=”0.4″,features=[“serde”]}

dotenv =”0.11.0″

diesel={version=”1.4″,features=[“postgres”,”r2d2″,”uuid”,”chrono”]}

diesel_migrations=”1.4.0″

env_logger=”0.6″

lazy_static=”1.4″

listenfd=”0.3″

log=”0.4″

serde=”1.0″

serde_json=”1.0″

r2d2=”0.8″

uuid={version=”0.6″,features=[“serde”,”v4″]}

futures=”0.3″

Rustings

https://github.com/rust-lang/rustlings

git clone -b 5.5.1 --depth 1 https://github.com/rust-lang/rustlings
cd rustlings
cargo install --force --path .

所有权、拷贝、智能指针、移动

image-20230707085733969

发表评论