rust基础常见60问

1,314 阅读7分钟
1.cargo如何更新到最新?
rustup update stable

2.cargo如何更新当前目录依赖到最新?
cargo update

3.如何显示rustc版本?
rustc -V 或者 rustc --version

4.如何显示cargo版本?
cargo -V 或者 cargo --version

5.如何修改cargo的代理地址?
在C:\Users\Administrator.cargo目录下面创建config文件, 并修改
http和https
[source.crates-io]
registry = "https://github.com/rust-lang/crates.io-index"
replace-with = 'ustc'
[source.ustc]
registry = "git://mirrors.ustc.edu.cn/crates.io-index"
[http]
proxy = "127.0.0.1:15035"
[https]
proxy = "127.0.0.1:15035"

[target.x86_64-pc-windows-gnu]
linker = "C:\msys64\mingw64\bin\gcc.exe"
ar = "C:\msys64\mingw64\bin\ar.exe"

6.如何创建一个新的rust项目?
cargo new helloworld

7.rustc的默认安装目录在哪里?
C:\Users\Administrator.cargo\bin

8.rustc如何打印一行字符串?
println!("Hello, world!");

9.rustc update之后产生的文件去哪里了?
C:\Users\Administrator.rustup

10.如何卸载rustc?
rustup self uninstall

11.如何进行rust镜像切换?
打开 config 文件,编写以下内容:
[source.crates-io]
registry = “https://github.com/rust-lang/crates.io-index”
replace-with = ‘ustc’
[source.ustc]
registry = “https://mirrors.ustc.edu.cn/crates.io-index”

12.如何查看已安装rust版本?
rustup toolchain list
会看到如下展示
$ rustup toolchain list
stable-x86_64-pc-windows-gnu
stable-x86_64-pc-windows-msvc (default)
nightly-x86_64-pc-windows-msvc

13.如何切换rust版本?
rustup default stable/nightly/beta
或者 rustup default stable-x86_64-pc-windows-gnu

14.如何安装rustfmt并且如何使用?
rustup component add rustfmt
cargo fmt

rustup component add rustfmt --toolchain stable

15.显示rust概况
rustup show

$ rustup show
Default host: x86_64-pc-windows-msvc
rustup home:  C:\Users\Administrator.rustup

installed toolchains
--------------------

stable-x86_64-pc-windows-gnu
stable-x86_64-pc-windows-msvc (default)
nightly-x86_64-pc-windows-msvc

installed targets for active toolchain
--------------------------------------

x86_64-pc-windows-gnu
x86_64-pc-windows-msvc
x86_64-unknown-linux-gnu

active toolchain
----------------

stable-x86_64-pc-windows-msvc (default)
rustc 1.54.0 (a178d0322 2021-07-26)

16.如何添加目标支持?
 If you meant to build software to target that platform, perhaps try `rustup target add gnu` instead?
$ rustup target add x86_64-pc-windows-msvc
$ rustup target add x86_64-pc-windows-gnu

17.rust里面如何写循环语句?
// `n` 将在每次迭代中分别取 1, 2, ..., 100
for n in 1..101 {
    if n % 15 == 0 {
        println!("fizzbuzz");
    } else if n % 3 == 0 {
        println!("fizz");
    } else if n % 5 == 0 {
        println!("buzz");
    } else {
        println!("{}", n);
    }
}

18.rust如何定义一个map, 以及map的增删改查?
let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Yellow"), 50);
for (key, value) in &scores {
    println!("{}: {}", key, value);
}
scores.remove(&String::from("Blue"));

for (key, value) in &scores {
    println!("{}: {}", key, value);
}


if scores.contains_key(&String::from("Blue")) {
    println!("We've got {} Blue.",
             scores.len());
}

let val: Option<&i32> = scores.get(&String::from("Yellow"));
println!("val =  {:?}", val);

19.Option是什么东西?
Option代表一个可选项值, 如果是Some表示有值, None表示没有值

20.如何获取Option里面的元素?
val.unwrap()可以返回里面的值, val.unwrap_or()也可以返回,如果没有返回一个默认值
let x : Option<i32> = Some(100);
println!("x = {}", x.unwrap());

let y : Option<&i32> = Some(&100);
println!("y = {}", y.unwrap());

x = 100
y = 100

21.如何指定版本更新?
rustup toolchain update stable-gnu
rustup toolchain update stable-msvc

22.变量前面加&是啥意思?
&加在类型前面表示引用。
&T:它是对类型 T 的不可变引用。&T 指针就是一种 Copy 类型,这只是意味着你
可以对类型 T 进行多次不可变引用。如果你将其赋给另一个变量,那么将得到一个
指针的副本,指向相同的数据。这对于指向引用的引用也一样,例如&&T

23.mut表示什么?
mut表示可变, 默认表示不可变。
&mut T:它是对类型 T 的可变引用。在任意作用域内部,根据借用规则,你不能
对类型 T 进行两次可变引用。这意味着&mut T 类型没有实现 Copy 特征。它们也
无法发送到线程。

24.pub关键字是什么意思?
在rust里面不带pub的结构体, 枚举是私有的; 带有pub的结构体是共有的,外部
可以对其进行访问
结构体Bar是共有的, 但是字段却是私有的
pub struct Bar {
    field: i32,
}

带pub的枚举, 里面的字段是可以被访问到的
pub enum State {
    PubliclyAccessibleState,
    PubliclyAccessibleState2,
}

25.derive是什么意思?
这是一个标识符,告诉编译器为结构体自动化生成一些特性,比如
#[derive(PartialEq, Clone)]
struct Foo<T> {
    a: i32,
    b: T,
}
可以自动化生成
impl<T: PartialEq> PartialEq for Foo<T> {
    fn eq(&self, other: &Foo<T>) -> bool {
        self.a == other.a && self.b == other.b
    }

    fn ne(&self, other: &Foo<T>) -> bool {
        self.a != other.a || self.b != other.b
    }
}

26.#[...]是啥意思?
这个表示结构体的属性

27.#[derive(Debug)]是意思是什么?
这个标识表示告诉编译器自动生成打印特性, 通过{:?}的方式对
结构体进行打印。
format!("Would the real {:?} please stand up!", Person { name: "John", age: 8 });.

28.format!是什么东西?
格式化字符串,返回值是一个String
println!("{}", format!("nihao"));


29.{:?}在rust里面表示什么?
这个标识符能够支持实现Debug特性格式化宏的值

30.PartialEq是什么意思?
如果我们想比较某个类型的两个值 x 和 y 是否相等(不等),
例如:x == y (x != y),那么我们就必须为类型实现 PartialEq Trait,
有点类似java的comparator, c++的相等重载运算符
enum BookFormat {
    Paperback,
    Hardback,
    Ebook,
}

struct Book {
    isbn: i32,
    format: BookFormat,
}

impl PartialEq for Book {
    fn eq(&self, other: &Self) -> bool {
        self.isbn == other.isbn
    }
}

let b1 = Book { isbn: 3, format: BookFormat::Paperback };
let b2 = Book { isbn: 3, format: BookFormat::Ebook };
let b3 = Book { isbn: 10, format: BookFormat::Paperback };

assert!(b1 == b2);
assert!(b1 != b3);

31.用clion必须下载stable-x86_64-pc-windows-gnu才行

32.卸载不需要的版本
rustup toolchain uninstall stable-x86_64-pc-windows-gnu
rustup toolchain uninstall 1.51.0-x86_64-pc-windows-gnu
rustup toolchain uninstall nightly-x86_64-pc-windows-msvc
如果是安装
rustup toolchain install stable-x86_64-pc-windows-gnu

33.rust访问mongodb?
mongodb默认是没有用户名和密码的, 需要自己进行设置
修改mongod.cfg,关闭安全性#security:
改成:
security:
        authorization: enabled
重启mongodb
加入path:D:\software\mongodb5.0\bin
进入mongo
show dbs
https://docs.mongodb.com/manual/reference/method/db.createUser/#examples
use admin
db.createUser(
   {
     user: "root",
     pwd: "admin123",
   }
)

34.assert_eq! meaning?
Asserts that two expressions are equal to each other

35.如何打印vec!?
let v2 = vec![1; 10];
println!("{:?}", v2);

36.move是什么意思?
move converts any variables captured by reference or mutable
reference to variables captured by value.

37.rust中双竖线是什么意思?
Rust的匿名函数由双竖线| |引出。双竖线中是匿名函数的参数列表,后面跟着匿名函数的表达式。
匿名函数的参数类型以及返回值类型通常可以忽略,交由编译器推断。有时编译器推断不出来,则需要
我们加上类型说明:
let square = |x: int| -> uint { x * x as uint };

38.表达式[x; N]含义?
A repeat expression [x; N], which produces an array with N copies of x.
The type of x must be Copy.

39.clion如何配置cargo工程?
选择cargo, name为项目名字, Command:run
Channel:default
working:E:\rust.learn\game|game
Backtrace:short

40.如何加速开发速度?
使用cargo check, 不生成二进制。

41.如何发布release构建
cargo build --release

42.如何下载依赖?
cargo build会自动下载依赖信息。

43.复制的配置为何无法识别?
没有对项目进行attach操作,重新打开项目进行attach

44.如何表示一个Range类型?
用start..end表示。

45._符号的作用?
_ + 变量名字, 会去掉警告, 不会释放所有权;
但是 _ = xx, 会释放所有权

46.String, &String, &mut String的区别?
String: 会移交所有权
&String: 引用, 不变引用
&mut String: 可变引用, 有且只有一个可变引用

47.如果声明变量?
使用let关键字声明一个变量

48.语句必须用分号结尾.

49.函数以fn作为关键字, 参数以"x:类型",方式进行声明, 返回值以"->类型"方式进行返回,
可以不用加"return关键字"返回函数值。

50.结构体以struct+stname{}的方式进行定义.
struct Rectangle {
    width: u32,
    height: u32,
}

51.不可变借用必须使用&+变量名的方式

52.{:#?}是什么意思?
{:#?}会对结构体进行缩进后再进行打印。

53.如何实现一个结构体的方法?
#[derive(Debug)]
struct Rectangle {
    width: u32,
    height: u32,
}
impl Rectangle {
    fn area(&self) -> u32 {
        return self.width * self.height
    }
}
如上使用impl关键字进行实现, 它们第一个参数总是 self,
它代表调用该方法的结构体实例

54.方法和关联函数的区别是是否带有self参数。

55.在rust里面枚举可以是任意类型, 比如整数,字符串,结构体,甚至元组类型。

56.gnu和msvc的差别
The GNU toolchain uses the MinGW build tools (mostly the linker)
and produces binaries that use the GNU ABI. The MSVC toolchain
uses the Visual Studio build tools and produces binaries that
use the Microsoft ABI, making them more compatible with most
other Windows binaries/libraries.

57.如何打印当前项目路径
fn get_current_working_dir() -> std::io::Result<PathBuf> {
    env::current_dir()
}

58.How to convert the PathBuf to String
let my_str = cwd.into_os_string().into_string().unwrap();

60.extern crate foo meaning?
extern crate foo indicates that you want to link against
an external library and brings the top-level crate name
into scope (equivalent to use foo). As of Rust 2018, in
most cases you won't need to use extern crate anymore
because Cargo informs the compiler about what crates
are present. (There are one or two exceptions)
use bar is a shorthand for referencing fully-qualified symbols.

Theoretically, the language doesn't need use — you could always just
fully-qualify the names, but typing std::collections::HashMap.new(...)
 would get very tedious! Instead, you can just type use
 std::collections::HashMap once and then HashMap will refer to that.