小编Luk*_*odt的帖子

使用函数指针时,"预期的fn项,找到了不同的fn项"

我有以下代码(游乐场):

// Two dummy functions, both with the signature `fn(u32) -> bool`
fn foo(x: u32) -> bool {
    x % 2 == 0
}
fn bar(x: u32) -> bool {
    x == 27
}


fn call_both<F>(a: F, b: F)
where
    F: Fn(u32) -> bool,
{
    a(5);
    b(5);
}

fn main() {
    call_both(foo, bar);  // <-- error
}
Run Code Online (Sandbox Code Playgroud)

对我来说,它看起来这应该是编译foobar具有相同的签名:fn(u32) -> bool.然而,我收到以下错误:

error[E0308]: mismatched types
  --> src/main.rs:20:20
   |
20 |     call_both(foo, bar);
   |                    ^^^ …
Run Code Online (Sandbox Code Playgroud)

rust

9
推荐指数
2
解决办法
990
查看次数

在Rust中检测平台

如何使用Rust检测操作系统类型?我需要指定一个特定于操作系统的默认路径.应该使用条件编译吗?

例如:

#[cfg(target_os = "macos")]
static DEFAULT_PATH: &str = "path2";
#[cfg(target_os = "linux")]
static DEFAULT_PATH: &str = "path0";
#[cfg(target_os = "windows")]
static DEFAULT_PATH: &str = "path1";
Run Code Online (Sandbox Code Playgroud)

cross-platform path rust

9
推荐指数
3
解决办法
2790
查看次数

为什么ops :: Range <T>不实现复制,即使T是复制?

最近,我想为3D投影编写一个类型保持参数:

use std::ops::Range;

#[derive(Clone, Copy)]
struct CamProj {
    /// Near and far plane
    proj_range: Range<f32>,
    /// Field of view
    fov: cgmath::Rad<f32>,     // `Rad` derives `Copy`
    /// Width divided by height
    aspect_ratio: f32,       
}
Run Code Online (Sandbox Code Playgroud)

但是,我收到了这个错误:

error[E0204]: the trait `Copy` may not be implemented for this type
 --> <anon>:3:21
  |
3 |     #[derive(Clone, Copy)]
  |                     ^^^^
...
6 |         proj_range: Range<f32>,
  |         ---------------------- this field does not implement `Copy`
Run Code Online (Sandbox Code Playgroud)

显然,Range<T>从来没有实现Copy,即使TCopy,就像f32是.这是为什么?我以为 …

rust

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

Rust中有POD类型的概念吗?

在C++中,术语POD类型用于描述仅包含普通旧数据的类型.引自这里:

没有构造函数,析构函数和虚拟成员函数的类[...].

Rust中有类似的概念吗?

rust

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

无法移出Fn闭包中捕获的外部变量

fn make_adder(x: String) -> Box<Fn() -> String> {
    Box::new(|| x)
}

fn main() {
    make_adder(String::from("a"));
}
Run Code Online (Sandbox Code Playgroud)

这导致此错误:

fn make_adder(x: String) -> Box<Fn() -> String> {
    Box::new(|| x)
}

fn main() {
    make_adder(String::from("a"));
}
Run Code Online (Sandbox Code Playgroud)

我该如何纠正?

rust

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

如何安全地从`&mut [u32]`获取不可变的字节片?

在我的项目的相当低级的部分中,函数接收可变的原始数据切片(&mut [u32]在这种情况下)。此数据应以小端序写入作者。

现在,仅此一项就不成问题,但是所有这些必须快速。我评估了我的应用程序,并将其确定为关键路径之一。特别是,如果不需要更改字节序(因为我们已经在一个小的字节序系统上),那么就不会有任何开销。

这是我的代码(Playground):

use std::{io, mem, slice};

fn write_data(mut w: impl io::Write, data: &mut [u32]) -> Result<(), io::Error> {
    adjust_endianness(data);

    // Is this safe?
    let bytes = unsafe {
        let len = data.len() * mem::size_of::<u32>();
        let ptr = data.as_ptr() as *const u8;
        slice::from_raw_parts(ptr, len)
    };

    w.write_all(bytes)
}

fn adjust_endianness(_: &mut [u32]) {
    // implementation omitted
}
Run Code Online (Sandbox Code Playgroud)

adjust_endianness更改位置的字节序(这很好,因为错误的字节序u32是垃圾,但仍然是有效的u32)。

该代码有效,但关键问题是:这样安全吗?特别是,在某个时刻,data并且bytes两者都存在,它们是同一数据的一个可变且一个不变的切片。听起来很不好,对吧?

另一方面,我可以这样做:

let bytes = &data[..];
Run Code Online (Sandbox Code Playgroud)

这样,我也有这两个方面。所不同的只是 …

unsafe rust

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

如何添加绑定到泛型关联类型的特征?

最近,Rust 博客上发表了“推动 GAT 稳定化”一文。我对这个LendingIterator特性很感兴趣,但在尝试使用它时遇到了问题。这是帖子中的定义:

trait LendingIterator {
    type Item<'a> where Self: 'a;
    fn next<'a>(&'a mut self) -> Option<Self::Item<'a>>;
}
Run Code Online (Sandbox Code Playgroud)

博客文章中宣传的所有内容都运行良好,我看到了 GAT 如何以多种方式提供帮助。但是:如何添加绑定到关联Item类型的特征?

使用标准Iterator特征,这很容易:

fn print_all<I>(mut i: I) 
where
    I: Iterator,
    I::Item: std::fmt::Debug,    // <-------
{
    while let Some(x) = i.next() {
        println!("{:?}", x);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是有了新特性,这个边界就不会编译(Playground):

where
    I: LendingIterator,
    I::Item: std::fmt::Debug,
Run Code Online (Sandbox Code Playgroud)

编译器说:

trait LendingIterator {
    type Item<'a> where Self: 'a;
    fn next<'a>(&'a mut self) -> Option<Self::Item<'a>>;
}
Run Code Online (Sandbox Code Playgroud)

所以我们需要一个生命周期参数。除了仅使用'static …

rust generic-associated-types

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

为什么我的stdin用户输入没有正确匹配?

我正在尝试获取系统输入并检查用户是否输入了是或否.我的字符串转换是错误还是什么?if块不执行.

use std::io;

fn main() {
    let mut correct_name = String::new();
    io::stdin().read_line(&mut correct_name).expect("Failed to read line");
    if correct_name == "y" {
        println!("matched y!");
    } else if correct_name == "n" {
        println!("matched n!");
    }
}
Run Code Online (Sandbox Code Playgroud)

rust

8
推荐指数
2
解决办法
1646
查看次数

为闭包实现特征会导致绑定/具体的生命周期不匹配

我想为特定类型的闭包实现一个特征.这是一个最小的例子(游乐场):

trait Foo {
    fn foo(&self, x: &u32);
}

impl<F> Foo for F
    where F: Fn(&u32)
{
    fn foo(&self, x: &u32) {
        self(x)
    }
}

fn main() {
    let _: &FnOnce(&u32) = &|x| {};   // works
    let _: &Foo          = &|x| {};   // doesn't work
}
Run Code Online (Sandbox Code Playgroud)

它导致此错误:

error: type mismatch resolving `for<'r> <[closure@<anon>:16:29: 16:35] as std::ops::FnOnce<(&'r u32,)>>::Output == ()`:
 expected bound lifetime parameter ,
    found concrete lifetime [--explain E0271]
  --> <anon>:16:28
   |>
16 |>     let _: &Foo          = …
Run Code Online (Sandbox Code Playgroud)

traits lifetime rust

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

无法克隆Vec <Box <Trait >>因为Trait无法成为对象

我正在尝试克隆盒装特征的向量.自然地简单地派生Clone所有实现我的特征的结构是不够的,因为编译器在编译时不知道实现特征的所有结构都有Clone.

好的,所以我接着尝试使用Clonesupertrait,但这只会导致标题中的错误.我对解决方案感到茫然.

这是最小工作实现(或不工作,因为我无法克隆)

#![allow(dead_code, unused_macros)]
use std::fmt::Debug;

trait MusicElement: Debug + Clone {
    fn duration(&self) -> f32;
}

#[derive(Debug, Clone)]
struct Note<'a> {
    name: &'a str,
    duration: f32,
}

impl<'a> MusicElement for Note<'a> {
    fn duration(&self) -> f32 {
        self.duration
    }
}

#[derive(Debug, Clone)]
struct Pause {
    duration: f32,
}

impl MusicElement for Pause {
    fn duration(&self) -> f32 {
        self.duration
    }
}

#[derive(Debug, Clone)]
struct Sequence {
    elements: Vec<Box<MusicElement>>,
}

impl MusicElement for …
Run Code Online (Sandbox Code Playgroud)

clone rust trait-objects

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