小编kmd*_*eko的帖子

如何将 Vec 解构为拥有所有权的变量?

我有一个结构

struct Foo {
    foo1: String,
    foo2: String,
    foo3: String,
    foo4: String,
    // ...
}
Run Code Online (Sandbox Code Playgroud)

我想Foo从向量创建一个实例。

let x = vec!["a".to_string(), "b".to_string(), "c".to_string(), "d".to_string()];
match x.as_slice() {
    &[ref a, ref b, ref c, ref d] => {
        let foo = Foo {
            foo1: a.to_string(),
            foo2: b.to_string(),
            foo3: c.to_string(),
            foo4: d.to_string(),
        };

    },
    _ => unreachable!(),
}
Run Code Online (Sandbox Code Playgroud)

我必须复制字符串吗?有没有更好的方法将向量解构为a, b, c,d并转移所有权?

事实上,我不介意x解构后被彻​​底摧毁。所以我希望除了切片之外还有向量的模式匹配。目前看来我们只能解构切片。

rust

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

如何在跟踪中使用动态跨度名称?

我需要动态地使用不同名称来检测跨度。如何创建具有动态命名的跟踪范围?

use tracing; // 0.1.22

fn main() {
    let name: &'static str = "foo bar";
    let span = tracing::span!(tracing::Level::TRACE, name);
    let span_handle = span.enter();
    tracing::info!("Hello, world!");
    drop(span_handle);
}
Run Code Online (Sandbox Code Playgroud)
error[E0435]: attempt to use a non-constant value in a constant
 --> src/main.rs:5:54
  |
5 |     let span = tracing::span!(tracing::Level::TRACE, name);
  |                                                      ^^^^ non-constant value
Run Code Online (Sandbox Code Playgroud)

操场

trace rust rust-tracing

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

标识符前面的::(双冒号)是什么意思?

该行来自 Rust libc crate。这里双冒号有什么用?我认为它c_uint从板条箱根引入范围,但我找不到它在板条箱根中定义的位置。

pub type speed_t = ::c_uint;
Run Code Online (Sandbox Code Playgroud)

syntax rust

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

为什么“临时是块末尾表达式的一部分”是一个错误?

这可能是我不理解借用检查器的一些技术细节的教科书案例,但如果有人能帮我解决这个问题会很好。

我有这个(令人难以置信的简化)代码块,它编译得非常好。

pub struct Example(pub Vec<String>);

impl Example {
  pub fn iter(&self) -> impl Iterator<Item=&String> {
    self.0.iter()
  }
}

pub fn some_condition(_: &str) -> bool {
  // This is not important.
  return false;
}

pub fn foo() -> bool {
  let example = Example(vec!("foo".to_owned(), "bar".to_owned()));
  let mut tmp = example.iter();
  tmp.all(|x| some_condition(x))
}

pub fn main() {
  println!("{}", foo());
}
Run Code Online (Sandbox Code Playgroud)

但是,我尝试的第一件事(在我看来,应该等同于上述内容)是tmp完全删除临时变量,如下所示

pub fn foo() -> bool {
  let example = Example(vec!("foo".to_owned(), "bar".to_owned()));
  example.iter().all(|x| some_condition(x))
}
Run Code Online (Sandbox Code Playgroud)

但是这个版本会产生以下错误。

pub struct …
Run Code Online (Sandbox Code Playgroud)

temporary rust borrow-checker

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

为什么对于简单的特征实现,我会收到“溢出评估需求”错误?

我收到了error[E0275]: overflow evaluating the requirement这个简单的代码,但我不知道如何解决它。错误消息建议为特征添加递归限制属性;但是,当我添加该属性时,它会生成一条新的错误消息,并建议我将递归限制加倍,直到它太大以至于rustc溢出堆栈。关于此错误已经有很多其他问题,但它们似乎与我的情况不同。

struct Foo<T>(T);

impl<T> From<&'_ Foo<T>> for String
where
    for<'a> &'a T: Into<String>,
{
    fn from(s: &Foo<T>) -> String {
        (&s.0).into()
    }
}

fn main() {
    println!("{}", String::from(&Foo(String::new())));
}
Run Code Online (Sandbox Code Playgroud)
error[E0275]: overflow evaluating the requirement `String: From<&'a Foo<_>>`
  --> src/main.rs:13:20
   |
13 |     println!("{}", String::from(&Foo(String::new())));
   |                    ^^^^^^^^^^^^
   |
   = help: consider adding a `#![recursion_limit="256"]` attribute to your crate (`playground`)
   = note: required because of the requirements on the impl of `for<'a> Into<String>` for …
Run Code Online (Sandbox Code Playgroud)

rust

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

是否可以定义一个与关键字同名的字段?

我正在使用 Rust 编写 REST API,我的 Flutter 客户端定义如下实体:

class WordDefinition {
  String type;
  String name;
  List<String> values;

  WordDefinition({
    this.type,
    this.name,
    this.values,
  });
}
Run Code Online (Sandbox Code Playgroud)

客户端用作type实体字段名称。在 Dart 中它工作正常,但在服务器端 Rust 我无法像这样定义字段名称:

use serde::{Deserialize, Serialize};

#[derive(Deserialize, Serialize)]
pub struct WordDefinition {
    pub type: String,
    pub text: String,
    pub translations: Vec<String>,
}
Run Code Online (Sandbox Code Playgroud)
use serde::{Deserialize, Serialize};

#[derive(Deserialize, Serialize)]
pub struct WordDefinition {
    pub type: String,
    pub text: String,
    pub translations: Vec<String>,
}
Run Code Online (Sandbox Code Playgroud)

我应该怎么做才能避免 Rust 关键字冲突?是否可以type在 Rust 中使用这样的方式定义实体名称?

rust serde

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

在匹配可变引用时,“mut”如何工作?

在下面的程序中,我试图理解matchmut, &do come in 时语句的复杂性。除此之外,就任何功能而言没有其他范围。

为了弄清楚变量的类型,我使用变量来调用函数checkout(n:i32)。编译器现在会抱怨 checkout Expects i32,但程序正在传递一些其他类型。我是一个新手,这是我认为我们可以找出我们没有明确提及的变量类型的一种方法。

fn checkout (k5:i32) {}

fn main() {
    let k5 = "learning rust".to_string();
    let k1 = Some(k5);
    match &mut k1 {
        Some(mut n) => {
            checkout(n);
            println!("the idea is {} {} ", n, n);
        }
        None => {}
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我编译程序,会出现以下错误消息

fn checkout (k5:i32) {}

fn main() {
    let k5 = "learning rust".to_string();
    let k1 = Some(k5);
    match &mut k1 {
        Some(mut n) => …
Run Code Online (Sandbox Code Playgroud)

match rust

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

如何为目标设置货物不稳定选项?

我有.cargo/config.toml以下内容:

\n
[unstable]\nunstable-options = true\nbuild-std = ["core", "alloc"]\n
Run Code Online (Sandbox Code Playgroud)\n

但我build-std只需要一个目标(例如thumbv7em-none-eabihf)。

\n

有没有办法专门为目标声明它?

\n

它可能是这样的:

\n
# wrong example, doesn\'t work apparently\n[target.thumbv7em-none-eabihf.unstable]\nbuild-std = ["core", "alloc"]\n
Run Code Online (Sandbox Code Playgroud)\n

注意,我\xe2\x80\x99m 仅讨论配置,我知道如何使用货物执行参数配置它。\xe2\x80\x99s 需要自动忽略build-std其他提到的目标,例如默认主机目标。

\n

config rust rust-cargo

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

Why does Stream provide convenience methods on an extension trait instead of the trait itself?

Consider the Iterator trait from the standard library:

pub trait Iterator {
    type Item;

    // required
    pub fn next(&mut self) -> Option<Self::Item>;

    // potentially advantageous to override
    pub fn size_hint(&self) -> (usize, Option<usize>) { ... }
    pub fn count(self) -> usize { ... }
    pub fn last(self) -> Option<Self::Item> { ... }
    pub fn advance_by(&mut self, n: usize) -> Result<(), usize> { ... }
    pub fn nth(&mut self, n: usize) -> Option<Self::Item> { ... }

    // convenience
    pub fn step_by(self, …
Run Code Online (Sandbox Code Playgroud)

traits rust

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

货物构建失败,= 注意:collect2:致命错误:找不到“ld”

我试图在 Ubuntu 上构建我的 Rust 项目并收到以下错误:

 = note: collect2: fatal error: cannot find 'ld'
          compilation terminated.


error: linking with `cc` failed: exit status: 1
Run Code Online (Sandbox Code Playgroud)

Ubuntu 版本 20.04 和 gcc 版本为:

gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/9/lto-wrapper
OFFLOAD_TARGET_NAMES=nvptx-none:hsa
OFFLOAD_TARGET_DEFAULT=1
Target: x86_64-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu 9.4.0-1ubuntu1~20.04' --with-bugurl=file:///usr/share/doc/gcc-9/README.Bugs --enable-languages=c,ada,c++,go,brig,d,fortran,objc,obj-c++,gm2 --prefix=/usr --with-gcc-major-version-only --program-suffix=-9 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-plugin --enable-default-pie --with-system-zlib --with-target-system-zlib=auto --enable-objc-gc=auto --enable-multiarch --disable-werror --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none=/build/gcc-9-yTrUTS/gcc-9-9.4.0/debian/tmp-nvptx/usr,hsa --without-cuda-driver --enable-checking=release …
Run Code Online (Sandbox Code Playgroud)

gcc rust rust-cargo

7
推荐指数
0
解决办法
2590
查看次数