小编Luk*_*odt的帖子

使用println打印字符的次数可变

我想使用println!强大的格式化工具format!来打印特定次数的字符.当然这可以通过循环来实现,如下所示:

fn give_love(count: usize) {
    print!("Here is love for you: ");
    for i in 0..count {
        print!("?");
    }
    println!("");
}
Run Code Online (Sandbox Code Playgroud)

但我既不想写循环也不想写三个print.如何更短/更好?

rust

5
推荐指数
3
解决办法
1039
查看次数

如何将路径列表传递给函数?

我想将目录名称列表传递给函数,如下所示:

use std::path::Path;

fn test(dirs: &Vec<Path>) {}

fn main() {
    let dirs = vec![Path::new("/tmp"), Path::new("/var/tmp")];
    test(dirs);
}
Run Code Online (Sandbox Code Playgroud)

但是它不能编译:

<anon>:3:5: 4:6 error: the trait bound `[u8]: std::marker::Sized` is not satisfied [E0277]
<anon>:3     fn test(dirs: &Vec<Path>) {
<anon>:4     }
<anon>:3:5: 4:6 help: see the detailed explanation for E0277
<anon>:3:5: 4:6 note: `[u8]` does not have a constant size known at compile-time
<anon>:3:5: 4:6 note: required because it appears within the type `std::sys::os_str::Slice`
<anon>:3:5: 4:6 note: required because it appears within the type …
Run Code Online (Sandbox Code Playgroud)

rust

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

使用修改后的`Chars`迭代器时,生命周期参数的数量错误

我想为IntoIterator包含a的结构实现trait String.迭代器基于chars()迭代器,应该计算'1'字符并累积结果.这是我到目前为止的简化版本:

use std::iter::Map;
use std::str::Chars;

fn main() {
    let str_struct = StringStruct { system_string: String::from("1101") };
    for a in str_struct {
        println!("{}", a);
    }
}

struct StringStruct {
    system_string: String
}

impl IntoIterator for StringStruct {
    type Item = u32;
    type IntoIter = Map<Chars, Fn(char) -> u32>;

    fn into_iter(self) -> Self::IntoIter {
        let count = 0;
        return self.system_string.chars().map(|c| match c {
            Some('1') => {
                count += 1;
                return Some(count);
            },
            Some(chr) => …
Run Code Online (Sandbox Code Playgroud)

iterator traits lifetime rust

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

Rust的词汇语法是常规的,无上下文的还是上下文敏感的?

大多数编程语言的词汇语法都是非常富有表现力的,以便快速掌握它.我不确定Rust的词汇语法属于什么类别.大多数似乎是常规的,可能除了原始字符串文字:

let s = r##"Hi lovely "\" and "#", welcome to Rust"##;
println!("{}", s);
Run Code Online (Sandbox Code Playgroud)

哪个印刷品:

Hi lovely "\" and "#", welcome to Rust
Run Code Online (Sandbox Code Playgroud)

因为我们可以任意添加许多#,看起来它不能正常,对吧?但语法是否至少没有上下文?或者是否有关于Rust的词汇语法的非上下文自由的东西?


相关:Rust的语法语法是无上下文还是上下文敏感?

grammar language-lawyer rust chomsky-hierarchy

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

元组实现`复制'吗?

在Rust Book,第18章中,他们举了一个模式匹配元组的例子.

fn print_coordinates(&(x, y): &(i32, i32)) {
    println!("Current location: ({}, {})", x, y);
}

fn main() {
    let point = (3, 5);
    print_coordinates(&point);   // point passed as reference
}
Run Code Online (Sandbox Code Playgroud)

出于好奇,我尝试了没有作为这样的参考传递.

fn print_coordinates((x, y): (i32, i32)) {
    println!("Current location: ({}, {})", x, y);
}

fn main() {
    let point = (3, 5);
    print_coordinates(point);   // point passed as value
    print_coordinates(point);   // point is still valid here
}
Run Code Online (Sandbox Code Playgroud)

它编译并打印出2次坐标.

元组是否可以像其他原始数据类型(数字,布尔值等)一样传递给函数?

tuples rust

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

实现proc宏时循环依赖包

我尝试实现Dump类似于serdes的proc_macro Serialize

为了这个目的,我有一个箱子foo包含我的“原始”结构(P1P2在这种情况下),这应该只是dumpable。

接下来,我确实有一个foo_derive包含程序宏本身的板条箱。

因为我想支持多种格式,所以我有第三个板条箱foo_dump,其中包含trait定义Dump(例如,可以转储此结构)和Dumper(这是后端应实现的)。非常直截了当的到这一点。

现在,我想编译它时,出现以下错误:

$ cargo build
error: cyclic package dependency: package `foo v0.1.0 (/tmp/tmp.u34pI5J6qd/example/foo)` depends on itself. Cycle:
package `foo v0.1.0 (/tmp/tmp.u34pI5J6qd/example/foo)`
    ... which is depended on by `foo_dump v0.1.0 (/tmp/tmp.u34pI5J6qd/example/foo_dump)`
    ... which is depended on by `foo_derive v0.1.0 (/tmp/tmp.u34pI5J6qd/example/foo_derive)`
Run Code Online (Sandbox Code Playgroud)

我不知道正确的方法是什么,如何在此板条箱中使用依赖项。我当前的是:

依存关系

这当然是不可能的。

我想念什么?我该怎么做才能打破依赖圈?


mcve @ github

/Cargo.toml

[workspace]
members = [ 
    "foo",
    "foo_derive",
    "foo_dump",
]
Run Code Online (Sandbox Code Playgroud)

/foo/Cargo.toml

[package]
name …
Run Code Online (Sandbox Code Playgroud)

rust rust-macros rust-proc-macros

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

为什么在为类型别名编写 impl 时会出现错误“无法为定义类型的包之外的类型定义固有的 `impl`”?

我希望实现 type 的功能OpResource

type OpResource = Object<OC, Status>;

impl OpResource {
    pub fn get_parameter_values(&self) -> Vec<ParameterValue> {
        self.spec
            .parameter_values
            .clone()
            .or_else(|| Some(vec![]))
            .unwrap()
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我得到一个错误

type OpResource = Object<OC, Status>;

impl OpResource {
    pub fn get_parameter_values(&self) -> Vec<ParameterValue> {
        self.spec
            .parameter_values
            .clone()
            .or_else(|| Some(vec![]))
            .unwrap()
    }
}
Run Code Online (Sandbox Code Playgroud)

我不明白我错在哪里,我只是实现了类型下面的函数,为什么它说我已经超出了箱子?

rust

5
推荐指数
0
解决办法
6275
查看次数

为什么在使用“ flat_map”时需要收集到向量中?

我正在研究Euler 96项目,以自学Rust。我已编写此代码以读取文件,并将其转换为整数向量(Playground)。

let file = File::open(&args[1]).expect("Sudoku file not found");
let reader = BufReader::new(file);

let x = reader
    .lines()
    .map(|x| x.unwrap())
    .filter(|x| !x.starts_with("Grid"))
    .flat_map(|s| s.chars().collect::<Vec<_>>())  // <-- collect here!
    .map(|x| x.to_digit(10).unwrap())
    .collect::<Vec<_>>();
Run Code Online (Sandbox Code Playgroud)

一切正常,但我感到困惑,为什么我必须将其收集到向量中flat_map(我假设创建不需要的向量,将其立即销毁是效率低下的)。如果我不收集,它将无法编译:

let file = File::open(&args[1]).expect("Sudoku file not found");
let reader = BufReader::new(file);

let x = reader
    .lines()
    .map(|x| x.unwrap())
    .filter(|x| !x.starts_with("Grid"))
    .flat_map(|s| s.chars().collect::<Vec<_>>())  // <-- collect here!
    .map(|x| x.to_digit(10).unwrap())
    .collect::<Vec<_>>();
Run Code Online (Sandbox Code Playgroud)

文档中的示例显示了几乎相同的代码,但不需要收集:

let words = ["alpha", "beta", "gamma"];

// chars() returns an iterator …
Run Code Online (Sandbox Code Playgroud)

lifetime rust borrow-checker

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

为何编译器以不同的方式对待这两条等效(?)行?

据我了解,x实现trait时Foo,以下两行应等效。

x.foo();
Foo::foo(&x);
Run Code Online (Sandbox Code Playgroud)

但是,我遇到的问题是编译器接受第一个,而拒绝第二个,并带有一个非常奇怪的错误消息。

与往常一样,此示例可在操场上找到

考虑以下两个相关特征。

pub trait Bar<'a> {
    type BarError: Into<MyError>;
    fn bar(&self) -> Result<(), Self::BarError>;
}

pub trait Foo: for<'a> Bar<'a> {
    type FooError: Into<MyError>;
    fn foo(&self) -> Result<(), Self::FooError>
    where
        for<'a> <Self as Bar<'a>>::BarError: Into<<Self as Foo>::FooError>;
}
Run Code Online (Sandbox Code Playgroud)

这个示例有点复杂,但是我确实需要使用生命周期参数Bar,而我不能使用它Foo。作为结果:

  • 我必须求助于高阶特质界限(HRTB);
  • 我不能依靠Bar::BarErrorFoo(实际上有类型无限多Bar<'_>::BarError),所以Foo必须有自己的FooError;
  • 所以我需要foo方法中绑定的复杂特征将BarErrors 转换为FooErrors。

现在,让我们来实现Bar,并Foo为具体的类型,例如 …

rust

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

如何在没有for循环的情况下获取迭代中正在处理的当前元素的索引?

我已阅读如何使用索引位置迭代 Vec<T>?答案是enumeratefor-loop 中使用。

但是,如果我不使用这样的for-loop:

fn main() {
    let v = vec![1; 10]
        .iter()
        .map(|&x| x + 1  /* + index */ ) // <--
        .collect::<Vec<_>>();

    print!("v{:?}", v);
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能在上面的闭包中获得索引?

rust

5
推荐指数
2
解决办法
2282
查看次数