我想在 Rust 中计算以下内容:
Python 等效项:
math.ceil(math.log(b+1, 2))
Run Code Online (Sandbox Code Playgroud)
我努力了:
a+1.log2()
(a+1).log2()
Run Code Online (Sandbox Code Playgroud)
但我得到了错误use of unstable library feature 'int_log'。我不想使用不稳定的库功能。如果可能的话,在没有任何外部板条箱的情况下计算 log2 最简单的方法是什么?
我知道我可以使用格式!创建一个带有变量的字符串。
let name = "rust";
format!("Hi, {}", name);
Run Code Online (Sandbox Code Playgroud)
但是,我使用原始字符串文字来生成 Json 格式的数据(这样我就不需要使用转义字符)。有没有办法在使用原始字符串文字时在字符串中使用变量?
我正在制作用于验证和计算 IP 的小程序。我想尝试模块,但遇到了一个错误,我不知道如何解决,并且在互联网上找不到任何内容。
这是我的项目结构:
src/
ip.rs
main.rs
mask.rs
show.rs
Run Code Online (Sandbox Code Playgroud)
ip.rs
src/
ip.rs
main.rs
mask.rs
show.rs
Run Code Online (Sandbox Code Playgroud)
显示.rs
pub struct Ip {
pub first: u8,
pub second: u8,
pub third: u8,
pub forth: u8,
pub bin: [bool; 32]
}
pub fn build_ip(ip: String) -> Ip {
let split = ip.replace(".", ":");
let split = split.split(":");
let split_vec = split.collect::<Vec<&str>>();
let mut bin: [bool; 32] = [false; 32];
let mut octets: [u8; 4] = [0; 4];
if split_vec.len() != 4 {
panic!("Wrong amount …Run Code Online (Sandbox Code Playgroud) 这是我的src文件夹结构
src/
|-- main.rs
|-- problems
| |-- mod.rs
| |-- p1.rs
| `-- p2.rs
`-- utilities.rs
Run Code Online (Sandbox Code Playgroud)
我的文件包含我在和utilities.rs中使用的 2 个函数。在 和 中都是行p1.rsp2.rsp1.rsp2.rs
#[path = "../utilities.rs"]
mod utilities;
Run Code Online (Sandbox Code Playgroud)
据我了解,允许我使用中定义的函数 中utilities.rs
定义的两个函数utilities.rs是
pub fn get_lines(num: &str) -> Vec<String> {...}
pub fn split(s: &String, separator: &str) -> Vec<String> {...}
Run Code Online (Sandbox Code Playgroud)
在p2.rs我同时使用它们,但在p1.rs我只使用get_lines. split当我运行或构建时,这会导致货物警告我“从未使用过”的功能,它是。但该函数已被使用,而且不仅在从未调用的函数中,所以我不明白为什么货物会警告我。看来我必须在包含自制模块的每个文件中使用每个模块函数,因为如果我确实调用,split则p1.rs警告就会消失。我不明白什么?
更清楚地说,问题是当我cargo run得到以下内容时
warning: function is never used: `split` …Run Code Online (Sandbox Code Playgroud) 我有这段简单的代码:
fn main() {
let mut blockchain: Vec<blockchain::Block> = Vec::new();
let genesis_block = blockchain::create_block("genesis_block");
blockchain::add_block_to_blockchain(&mut blockchain, genesis_block);
}
Run Code Online (Sandbox Code Playgroud)
我的错误发生在这里:
pub fn get_last_block(blockchain: &Vec<Block>) -> Block {
return blockchain[blockchain.len() - 1];
}
Run Code Online (Sandbox Code Playgroud)
它说:
我对 Rust 还很陌生,所以有人可以解释一下为什么这不起作用吗?
我只是想获取这个向量的最后一个元素。
我应该传递这个向量的所有权而不是借用它吗?
编辑:这是我现在的结果:
pub fn get_last_block(blockchain: &Vec<Block>) -> Option<&Block> {
return blockchain.last();
}
Run Code Online (Sandbox Code Playgroud)
blockchain可能是空的。我检查is_some它是否返回一个值
let block = blockchain::get_last_block(&blockchain);
if block.is_some() {
blockchain::print_block(block.unwrap());
}
Run Code Online (Sandbox Code Playgroud) 我func1, func2, func3在结构对象上有 3 种不同的异步方法。
我想要完成的是这样的:
loop {
obj.func1().await;
set_timeout(Duration::from_secs(5)).await;
}
loop {
obj.func2().await;
set_timeout(Duration::from_secs(5)).await;
}
loop {
obj.func3().await;
set_timeout(Duration::from_secs(5)).await;
}
Run Code Online (Sandbox Code Playgroud)
我希望所有这 3 个循环并行运行。显然,在这种形式下它不起作用,因为第二个和第三个循环将无法到达。
我想到了以下解决方案:
loop {
thread::spawn(move || async move {
obj.func1().await;
obj.func2().await;
obj.func3().await;
set_timeout(Duration::from_secs(5)).await;
});
}
Run Code Online (Sandbox Code Playgroud)
但它有两个问题:
Copy特征(使用一些第三方板条箱,因此不能在那里做太多事情)。我应该如何处理这个问题?
我在阅读 Rust 时遇到了这个特征定义:
trait Enchanter: std::fmt::Debug {
...
}
Run Code Online (Sandbox Code Playgroud)
由此我了解到该特征的名称是Enchanter,但我不明白该std::Format:Debug部分意味着什么,因为它也是一个特征(我认为)。
我有两个结构。第一个“父”结构包含需要显式清理的资源,我通过派生Drop特征来处理该资源。第二个“子”结构是从父结构中检索的,并且需要该资源尚未被释放才能有效。
换句话说,任何父实例的寿命都必须比其子实例的寿命长。
\n我的解决方案使用引用来使借用检查器强制执行此规则。
\nstruct Parent {\n // Private resource data.\n}\n\nimpl Parent {\n fn new() -> Self {\n Parent {}\n }\n\n fn new_child(&self) -> Child {\n return Child { _parent: self };\n }\n}\n\nimpl Drop for Parent {\n fn drop(&mut self) {\n // Do some cleanup after which no instance of Child will be valid.\n }\n}\n\nstruct Child<\'a> {\n _parent: &\'a Parent,\n // Private data.\n}\n\nimpl<\'a> Child<\'a> {\n fn hello(&self) {\n println!("Hello Child!");\n }\n}\n\nfn main() {\n let parent = …Run Code Online (Sandbox Code Playgroud) 根据Rust Lang 编程书籍,我们知道:
&self 实际上是 self 的缩写:&Self
但是,从下面的示例( )中,根据错误消息,fn get_name我们编写的self: &Self, but不是引用而是对象本身。self为什么在这种情况下没有self参考?那么其中的&符号是做什么用的&Self呢?
示例:一个简单的结构体,其方法返回一个人的名字
struct Person {
name: String
}
impl Person {
fn new(name: &str) -> Person {
Person {
name: name.to_string()
}
}
fn get_name(self: &Self) -> &String {
self.name // Error: expected `&std::string::String`, found struct `std::string::String`
}
}
Run Code Online (Sandbox Code Playgroud) 我正在通过Make a Lisp来学习 Rust。
\n作为评估器步骤的一部分,我需要创建一个将字符串(或其他内容)映射到函数的关联结构。在我更熟悉的语言(Ruby、Clojure)中,我会简单地在哈希图中定义匿名函数,例如
\n{ :+ (fn [a b] (+ a b))\n :- (fn [a b] (- a b)) } ; etc\nRun Code Online (Sandbox Code Playgroud)\n在 Rust 中,由于类型错误,这是不可能的expected closure, found a different closure。
let repl_env = HashMap::new();\n\nrepl_env.insert("+", |a, b| a + b);\nrepl_env.insert("-", |a, b| a - b); // expected closure, found a different closure\nRun Code Online (Sandbox Code Playgroud)\n我想这里发生的事情是
\nHashMap编译器正在推断as中的类型<String, WhateverTypeTheFirstClosureIs>no two closures, even if identical, have the …