相关疑难解决方法(0)

iter和into_iter有什么区别?

我正在做Rust示例教程,其中包含以下代码片段:

// Vec example
let vec1 = vec![1, 2, 3];
let vec2 = vec![4, 5, 6];

// `iter()` for vecs yields `&i32`. Destructure to `i32`.
println!("2 in vec1: {}", vec1.iter()     .any(|&x| x == 2));
// `into_iter()` for vecs yields `i32`. No destructuring required.
println!("2 in vec2: {}", vec2.into_iter().any(| x| x == 2));

// Array example
let array1 = [1, 2, 3];
let array2 = [4, 5, 6];

// `iter()` for arrays yields `&i32`.
println!("2 in array1: {}", array1.iter() …
Run Code Online (Sandbox Code Playgroud)

rust

117
推荐指数
4
解决办法
2万
查看次数

在变量名之前和":"之后放置"mut"有什么区别?

这是我在Rust文档中看到的两个函数签名:

fn modify_foo(mut foo: Box<i32>) { *foo += 1; *foo }
fn modify_foo(foo: &mut i32) { *foo += 1; *foo }
Run Code Online (Sandbox Code Playgroud)

为什么不同的位置mut

似乎第一个函数也可以声明为

fn modify_foo(foo: mut Box<i32>) { /* ... */ }
Run Code Online (Sandbox Code Playgroud)

variables syntax reference mutable rust

51
推荐指数
3
解决办法
5734
查看次数

如何解决不能借用可变的问题,因为它位于“&amp;”引用后面

我是 Rust 新手,正在尝试学习和实验,这里是游乐场的链接,其中包含以下问题和解释:https: //play.rust-lang.org/ ?version=stable&mode=debug&edition=2018&gist=19920813410a42500045cf2c6cc94f12

use std::fmt;

#[derive(Clone, Copy)]
struct Animal<'a> {
    name: &'a str
}

impl <'a>Animal<'a> {
    fn new(name: &'a str) ->  Self { Self { name } }    
}
struct Barn<'a> {
    name: &'a str,
    animals: Vec<Animal<'a>>
}

impl <'a> Barn<'a> {
    fn new(name: &'a str, animals: Vec<Animal<'a>>) ->  Self { Self { name, animals } }    
}

impl <'a>fmt::Debug for Barn<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.name)
    }
}

struct …
Run Code Online (Sandbox Code Playgroud)

rust

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

标签 统计

rust ×3

mutable ×1

reference ×1

syntax ×1

variables ×1