我正在做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文档中看到的两个函数签名:
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) 我是 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)