相关疑难解决方法(0)

为什么不鼓励接受对String(&String),Vec(&Vec)或Box(&Box)的引用作为函数参数?

我写了一些Rust代码&String作为参数:

fn awesome_greeting(name: &String) {
    println!("Wow, you are awesome, {}!", name);
}
Run Code Online (Sandbox Code Playgroud)

我还编写了代码来引用a Vec或Box:

fn total_price(prices: &Vec<i32>) -> i32 {
    prices.iter().sum()
}

fn is_even(value: &Box<i32>) -> bool {
    **value % 2 == 0
}
Run Code Online (Sandbox Code Playgroud)

但是,我收到一些反馈意见,这样做并不是一个好主意.为什么不?

string reference rust borrowing

100
推荐指数
2
解决办法
5549
查看次数

如何匹配Rust中的struct字段?

Rust可以匹配struct字段吗?例如,这段代码:

struct Point {
    x: bool,
    y: bool,
}

let point = Point { x: false, y: true };

match point {
    point.x => println!("x is true"),
    point.y => println!("y is true"),
}
Run Code Online (Sandbox Code Playgroud)

应该导致:

y is true
Run Code Online (Sandbox Code Playgroud)

rust

10
推荐指数
2
解决办法
5396
查看次数

如果我不在乎枚举字段,如何断言枚举是特定变量?

我想检查测试中具有字段的枚举,而现在暂时忽略字段的实际值。

考虑以下示例:

enum MyEnum {
    WithoutFields,
    WithFields { field: String },
}

fn return_with_fields() -> MyEnum {
    MyEnum::WithFields {
        field: "some string".into(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn example() {
        assert_eq!(return_with_fields(), MyEnum::WithFields {..});
    }
}
Run Code Online (Sandbox Code Playgroud)

操场

我想assert_eq!在这里使用,但是编译器告诉我:

enum MyEnum {
    WithoutFields,
    WithFields { field: String },
}

fn return_with_fields() -> MyEnum {
    MyEnum::WithFields {
        field: "some string".into(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn example() {
        assert_eq!(return_with_fields(), MyEnum::WithFields {..});
    }
} …
Run Code Online (Sandbox Code Playgroud)

rust

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

标签 统计

rust ×3

borrowing ×1

reference ×1

string ×1