2

【Rust2】包、Crate、模块

 1 year ago
source link: https://www.guofei.site/2022/08/28/rust2.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

【Rust2】包、Crate、模块

2022年08月28日    Author:Guofei

文章归类: 语言    文章编号: 19002


版权声明:本文作者是郭飞。转载随意,但需要标明原文链接,并通知本人
原文链接:https://www.guofei.site/2022/08/28/rust2.html

Edit
use std::fmt::Result;
use std::io::Result as IoResult;

// 引用多个
use std::{cmp::Ordering, io};

use std::io::{self, Write};
// 上面的等价于:
use std::io;
use std::io::Write;

use std::collections::*;
mod front_of_house {
  // 默认私有,加 pub 后才能让外面使用
    pub mod hosting {
        pub fn add_to_waitlist() {}
    }
}

// use 前面加 pub 是重导出。调用这段代码时,也能调这个
pub use crate::front_of_house::hosting;

pub fn eat_at_restaurant() {
    hosting::add_to_waitlist();
    hosting::add_to_waitlist();
    hosting::add_to_waitlist();
}

如何引入包

文件名 Cargo.toml

[dependencies]
rand = "0.8.3"

如何做包

pub mod mod_name1 {
    pub mod mod_name1_1 {
        pub fn func1() {
            println!("run: func1");
        }
    }
}

pub fn main() {
    mod mod_name {
        pub mod mod_name2 {
            pub fn func1() {
                println!("run: func1 in self")
            }
        }
    }

    // 可以有多个子模块
    mod mod_name3 {
        // 这里没加pub,下面就不能调用
        fn func3() {}
    }

    pub fn func4() {
        // 绝对路径
        crate::mod_name1::mod_name1_1::func1();

        // 相对路径
        mod_name::mod_name2::func1();
    }

    func4();
}

多文件

可以把代码做到另一个文件中 my_mod1.rs

pub mod mod_in_file {
    pub fn my_func1() {
        println!("my_func1 in file!");
    }
}

lib.rs这样写

// ??我理解这个相当于关联那个文件,没有这个直接用use是不行的
pub mod my_mod1;

// 然后可以use了,也可以不用
pub use crate::my_mod1::mod_in_file::my_func1;

// 可以在lib里面做进一步处理
pub fn my_func2() {
    println!("my_mod1!");
    // my_mod1::my_func1();
    crate::my_mod1::mod_in_file::my_func1();
}

main.rs 里面这样引用

mod my_mod1;

一些基本配置问题

Blocking waiting for file lock on package cache

  • rm -rf ~/.cargo/registry/index/*
  • rm -rf ~/.cargo/.package-cache

Updating crates.io index 卡住

  • 把crates.io换国内的镜像源
  • vim ~/.cargo/config,修改为下面的
# 放到 `$HOME/.cargo/config` 文件中
[source.crates-io]
#registry = "https://github.com/rust-lang/crates.io-index"

# 替换成你偏好的镜像源
replace-with = 'ustc'
#replace-with = 'sjtu'

# 清华大学
[source.tuna]
registry = "https://mirrors.tuna.tsinghua.edu.cn/git/crates.io-index.git"

# 中国科学技术大学
[source.ustc]
registry = "git://mirrors.ustc.edu.cn/crates.io-index"

# 上海交通大学
[source.sjtu]
registry = "https://mirrors.sjtug.sjtu.edu.cn/git/crates.io-index"

# rustcc社区
[source.rustcc]
registry = "git://crates.rustcc.cn/crates.io-index"

参考

https://rustwiki.org/zh-CN/book/ch03-05-control-flow.html

您的支持将鼓励我继续创作!

qr.jpeg

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK