小编caf*_*e25的帖子

解析 Rust 中的属性宏参数

我正在编写一个属性宏并尝试解析那里传递的参数。

喜欢:#[macro(Arg1, Arg2)]

问题是我找不到正确的结构来解析它。我尝试将其解析为MetaandMetaList但它们似乎都不起作用。

pub fn some_macro(args: TokenStream, item: TokenStream) -> TokenStream {
let args_parsed = parse_macro_input!(args as MetaList);

////////

let args_parsed = parse_macro_input!(args as Meta);

}
Run Code Online (Sandbox Code Playgroud)

当我解析它时,MetaList我得到:“意外的输入结束,预期的括号”错误。

rust rust-macros

2
推荐指数
1
解决办法
3726
查看次数

如何在 Rust 中连接来自不同类型的多个部分的 Path?

文档提供了以下连接路径的示例:

use std::path::PathBuf;

let path: PathBuf = [r"C:\", "windows", "system32.dll"].iter().collect();
Run Code Online (Sandbox Code Playgroud)

当所有组件都是字符串时,这才有效。但是,我正在尝试编写以下函数:

use std::path::PathBuf;
fn my_path<P: AsRef<Path>>(root: P, dir1: &str, dir2: &str, dir3: &str) -> PathBuf {
    [root, dir1, dir2, dir3].iter().collect()
}
Run Code Online (Sandbox Code Playgroud)

上面的显然不行。我知道我可以进行一系列嵌套连接,但那就是……更丑陋。

有没有办法在数组中加入不同的类似路径的组件?

rust

2
推荐指数
1
解决办法
462
查看次数

将 Either 列表映射到整数

我正在尝试执行以下操作:

processRights :: [Either a Int] -> Int
processRights xs = map (\Right x -> x, \Left x -> 0) xs
Run Code Online (Sandbox Code Playgroud)

所以,xs是 a [Either a Int],我希望生成一个相同长度的映射列表,其中每个 int 都有相同的 int,否则为 0。

我怎样才能做到这一点?

lambda haskell either

2
推荐指数
1
解决办法
130
查看次数

带引脚和不带引脚的比较功能

我试图理解 Rust 中的 Pin https://doc.rust-lang.org/std/pin/

主要思想很清楚 如果我们有Pin<T>那么类型的指针T就不能移动

Pin我正在编写一个带有和不带有for 的函数Box。我有完全相同的结果。如何修改代码才能看到效果Pin

use std::fmt::{self, Debug};
use std::pin::Pin;

fn foo_pin<T: Debug>(s: Pin<Box<T>>) {
    let copys = s;
    println!("Hi from Box: {:?}", copys); 
    //println!("Hi from Box: {:?}", s); // ERROR borrow of moved value: `s`
}

fn foo<T: Debug>(s: Box<T>) {
    let copys = s;
    println!("Hi from Box: {:?}", copys); 
    //println!("Hi from Box: {:?}", s); // ERROR borrow of moved value: `s`
}

fn main() …
Run Code Online (Sandbox Code Playgroud)

rust

2
推荐指数
1
解决办法
55
查看次数

使用概念区分一维和二维容器

我想使用概念来区分一维和二维容器。我的第一次尝试如下:

template<typename C>
concept Container1D = requires(C c) {
    std::begin(c);
    std::end(c);
    c[0];
};

template<typename C>
concept Container2D = requires(C c) {
    std::begin(c);
    std::end(c);
    c[0, 0]; // interpreted as comma-operator
};
Run Code Online (Sandbox Code Playgroud)

但显然这不起作用,因为表达式0, 0被解释为逗号运算符,因此第二个概念也匹配一维容器。

有没有办法要求二维operator[a, b]

c++ containers concept c++23

2
推荐指数
1
解决办法
76
查看次数

When can string slice `&amp;str` produced by a function be returned in Rust?

I've managed to cook up three scenarios which to me seem on the surface to be the same, but behave differently, and I would appreciate if someone could clarify to me why...

The first scenario fails to complile, as I would actually expect :

fn main() {
    let data = get_data();
    println!("{}", data);
}

fn get_data() -> &'static str {
    let x: String = String::from("hello");
    return x.as_str(); // always fails with ownership issue
}
Run Code Online (Sandbox Code Playgroud)

Fails as expected: returns a reference …

rust

2
推荐指数
1
解决办法
123
查看次数

当两者都有效时,为什么 Rust 编译器建议添加“&amp;”而不是“*”?

我用 Rust 编写了一个简单的程序。这个程序可以编译。

use std::cell::{Ref, RefCell};

fn print_number(x: &i32) {
    println!("x is {}", x);
}

fn main() {
    let stack: i32 = 42;
    let reference: &i32 = &stack;
    let refcell: RefCell<&i32> = RefCell::new(reference);
    let wrapped: Ref<'_, &i32> = refcell.borrow();

    print_number(&wrapped);
    print_number(*wrapped);
}
Run Code Online (Sandbox Code Playgroud)

我可以说出两者都有效的原因:

  1. &有效,因为&wrapped的类型为&Ref<&i32>,可以被解引用强制为&&i32,也可以被解引用强制为&i32
  2. *有效,因为*wrapped相当于*Deref::deref(&wrapped). 我们知道Deref::deref(&Ref<&i32>)结果为&&i32,因此*Deref::deref(&Ref<&i32>)结果为*&&i32,即&i32

似乎第二种方法(使用*)更直接,但是 Rust 编译器建议我使用第一种方法(使用&)。如果我添加一行:

print_number(wrapped);
Run Code Online (Sandbox Code Playgroud)

这当然不能编译。但我对编译器报告感兴趣:

error[E0308]: …
Run Code Online (Sandbox Code Playgroud)

dereference rust

2
推荐指数
1
解决办法
106
查看次数

在 HashMap 中,结构体属性作为键,结构体本身作为值

下面是一段更复杂的代码片段,其思想是加载一个 SQL 表并设置一个哈希图,其中一个表结构字段作为键,并将结构保留为值(实现细节并不重要,因为代码工作正常但是,如果我克隆String,数据库中的字符串可以是任意长,并且克隆可能会很昂贵)。

以下代码将失败并显示

error[E0382]: use of partially moved value: `foo`
  --> src/main.rs:24:35
   |
24 |         foo_hashmap.insert(foo.a, foo);
   |                            -----  ^^^ value used here after partial move
   |                            |
   |                            value partially moved here
   |
   = note: partial move occurs because `foo.a` has type `String`, which does not implement the `Copy` trait

For more information about this error, try `rustc --explain E0382`.
Run Code Online (Sandbox Code Playgroud)
error[E0382]: use of partially moved value: `foo`
  --> src/main.rs:24:35
   |
24 |         foo_hashmap.insert(foo.a, foo);
   |                            ----- …
Run Code Online (Sandbox Code Playgroud)

struct rust

1
推荐指数
1
解决办法
1041
查看次数

将 u128 复制到 [u64;2]

如何u128将 a 转换为 s 数组u64。当将 a 传递u128给采用任意精度 int 的 API 时,该 API 需要 3 个参数

LLVMValueRef LLVMConstIntOfArbitraryPrecision   (
  LLVMTypeRef IntTy,
  unsigned  NumWords,
  const uint64_t Words[] 
)
Run Code Online (Sandbox Code Playgroud)

前两个参数已知(IntTy=LLVMInt128TypeNumWords= 2)。第三个参数需要一个 s 数组uint64_t。提供的u128需要转换为u64的数组。从rust 文档来看,它似乎u128可以转换为字节数组,例如

let buff: [u8; 16] = u128_val.to_ne_bytes();
let Words: [u64; 2] = ?? // What to do here?
Run Code Online (Sandbox Code Playgroud)

如何buff转换为数组Words?另外,如何处理字节序。为简单起见,代码生成器和 API 将在具有相同字节序的机器上运行。

types arbitrary-precision rust

1
推荐指数
1
解决办法
623
查看次数

解析输入中的浮点值会导致“异常:无解析”

我写了这段代码:

\n
calculIOTest :: IO ()\ncalculIOTest = do\n   putStrLn "Give me two numbers"\n   l1 <- getLine\n   let x1 = read l1 \n   l2 <- getLine\n   let x2 = read l2 \n   print (x1 + x2)\n
Run Code Online (Sandbox Code Playgroud)\n

我想要接受两个数字并返回总和的代码。如果我用两个整数测试我的函数,它可以工作,但如果我放置一个浮点数,则会出现错误问题:

\n
calculIOTest :: IO ()\ncalculIOTest = do\n   putStrLn "Give me two numbers"\n   l1 <- getLine\n   let x1 = read l1 \n   l2 <- getLine\n   let x2 = read l2 \n   print (x1 + x2)\n
Run Code Online (Sandbox Code Playgroud)\n

我本来可以用字符串和数字来理解,但在这里我很难理解导致问题的原因。

\n

我试图回顾一下 read 是如何工作的,如果我这样做的话:

\n
***Exception: Prelude.read: …
Run Code Online (Sandbox Code Playgroud)

io haskell

1
推荐指数
1
解决办法
90
查看次数