我写了一个max函数,它接受Vec一个参数.它按我的预期工作.然后我添加了一个与min函数相同的max函数:
fn main() {
let my_array = vec![61, 14, 71, 23, 42, 8, 13, 66];
let max = max(my_array);
let min = min(my_array);
println!("Max value is {}.", max);
}
fn max(array: Vec<i32>) -> i32 {
let mut max = array[0];
for val in array {
if max < val {
max = val;
}
}
max
}
fn min(array: Vec<i32>) -> i32 {
let mut min = array[0];
for val in array{ …Run Code Online (Sandbox Code Playgroud) 您可以String使用contains搜索模式的方法来执行此操作,但是Vec::contains针对单个元素.
我能够做到这一点的唯一方法是直接实现某种子串函数,但我有点希望有一种内置方式.
let vec1 = vec![1, 2, 3, 4, 5];
let vec2 = vec![2, 3]; // vec2 IS a substring of vec1
let vec3 = vec![1, 5]; // vec3 is NOT a substring of vec3
fn is_subvec(mainvec: &Vec<i32>, subvec: &Vec<i32>) -> bool {
if subvec.len() == 0 { return true; }
if mainvec.len() == 0 { return false; }
'outer: for i in 0..mainvec.len() {
for j in 0..subvec.len() {
if mainvec[i+j] != subvec[j] …Run Code Online (Sandbox Code Playgroud) 我有一个阅读文件内容的功能.我需要通过引用从这个函数返回内容,我只是无法弄清楚如何String在函数内创建具有一定生命周期的mutable .
fn main() {
let filename = String::new();
let content: &String = read_file_content(&filename);
println!("{:?}", content);
}
fn read_file_content<'a>(_filename: &'a String) -> &'a String {
let mut content: &'a String = &String::new();
//....read file content.....
//File::open(filename).unwrap().read_to_string(&mut content).unwrap();
return &content;
}
Run Code Online (Sandbox Code Playgroud)
输出:
error[E0597]: borrowed value does not live long enough
--> src/main.rs:8:36
|
8 | let mut content: &'a String = &String::new();
| ^^^^^^^^^^^^^ does not live long enough
...
14 | }
| - temporary value only lives …Run Code Online (Sandbox Code Playgroud) 我检查doc中的Index trait并找到index()is的返回类型&T.
然后我写这个函数来从vector获取值:
fn get_value_test(a: usize, v: &Vec<i32>) -> i32 {
v[a]
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:为什么v[a]是i32不过&i32?因为i32 ...have a known size at compile time are stored entirely on the stack, so copies of the actual values are quick to make?(从这里)
看起来Rust在这种情况下有隐藏规则转换类型?
我正在尝试实现一个函数,以将包含模式的所有字符串的向量从(Vec<String>)返回到另一个Vec<String>。
这是我尝试的:
fn select_lines(pattern: &String, lines: &Vec<String>) -> Vec<String> {
let mut selected_lines: Vec<String> = Vec::new();
for line in *lines {
if line.contains(pattern) {
selected_lines.push(line);
}
}
selected_lines
}
Run Code Online (Sandbox Code Playgroud)
导致在for循环的行上出现错误(*行)。我是Rust的新手(昨天开始学习Rust!),现在对解决该错误几乎一无所知。
我可以删除,*并且该错误消失了,但是有关类型不匹配的错误开始达到高潮。我想保持功能的签名完整。有办法吗?
结构定义为:
struct Node {
set: HashSet<usize>,
// other fields omitted
}
Run Code Online (Sandbox Code Playgroud)
我必须为特征(兼容性问题)实现一个函数,该函数需要将集合中的所有元素作为切片返回。
我知道以下功能将无法正常工作:
impl Node {
pub fn set_slice(&self) -> &[usize] {
let elems: Vec<_> = self.set.iter().cloned().collect();
&elems[..]
}
}
Run Code Online (Sandbox Code Playgroud)
问题是:
struct Node {
set: HashSet<usize>,
// other fields omitted
}
Run Code Online (Sandbox Code Playgroud)
我知道这个要求听起来很奇怪。尽管为什么我必须这样做,是否有任何“好的”方式来实现这一目标?
如果有可能,我想保留该HashSet容器以进行O(1)查找,并且我不想引入新的struct成员以节省内存。
我正在编写一个程序,它的字符串处理功能可能有点太多了。我将大部分文字消息移至常量;我不确定这在 Rust 中是否正确,但我习惯用 C 编写。
我发现我不能轻易地使用我的static &str内部match表达式。我可以使用文本本身,但不知道如何正确地做到这一点。
我知道这是一个编译器问题,但不知道如何以 Rust 风格正确编写该结构。我应该使用枚举而不是类似 C 的静态变量吗?
static SECTION_TEST: &str = "test result:";
static STATUS_TEST_OK: &str = "PASSED";
fn match_out(out: &String) -> bool {
let s = &out[out.find(SECTION_TEST).unwrap() + SECTION_TEST.len()..];
match s {
STATUS_TEST_OK => {
println!("Yes");
true
}
_ => {
println!("No");
false
}
}
}
Run Code Online (Sandbox Code Playgroud)
static SECTION_TEST: &str = "test result:";
static STATUS_TEST_OK: &str = "PASSED";
fn match_out(out: &String) -> bool {
let s = &out[out.find(SECTION_TEST).unwrap() + SECTION_TEST.len()..];
match …Run Code Online (Sandbox Code Playgroud) 我正在编写一个 Rust 程序,它将根据用户输入创建一个目录。我想知道panic当发生时如何处理我自己的文本error,比如Permission Error等等......
fn create_dir(path: &String) -> std::io::Result<()> {
std::fs::create_dir_all(path)?;
Ok(())
}
Run Code Online (Sandbox Code Playgroud)
error发生此情况时不会执行任何操作
我想在 Rust 中实现一个函数,计算数组或 Vec 的范数
对于 Vec<f64> 我会将函数写为
pub fn vector_norm( vec_a : &Vec<f64> ) -> f64 {
let mut norm = 0 as f64;
for i in 0..vec_a.len(){
norm += vec_a[i] * vec_a[i];
}
norm.sqrt()
}
Run Code Online (Sandbox Code Playgroud)
对于 &[f64] 我会做
pub fn vector_norm( vec_a : &[f64] ) -> f64 {
let mut norm = 0 as f64;
for i in 0..vec_a.len(){
norm += vec_a[i] * vec_a[i];
}
norm.sqrt()
}
Run Code Online (Sandbox Code Playgroud)
但是有没有办法通过使用特征将两个版本组合成一个函数。我在想类似的事情
pub fn vector_norm<T:std::iter::ExactSizeIterator>
( vec_a : &T ) -> f64 …Run Code Online (Sandbox Code Playgroud) Copy在Rust 中缺少的元素的借入向量上计算算术运算的正确方法是什么?在下面的代码中,我想foo借用一个向量x,然后计算一个短函数。诀窍在于元素中x必然缺少Copy特质。无论如何,代码
fn foo<Real>(x: &Vec<Real>) -> Real
where
Real: std::ops::Add<Output = Real> + std::ops::Mul<Output = Real> + Clone,
{
(x[0] + x[1]) * x[2]
}
fn main() {
let x = vec![1.2, 2.3, 3.4];
let _y = foo::<f64>(&x);
}
Run Code Online (Sandbox Code Playgroud)
无法编译错误
error[E0507]: cannot move out of index of `std::vec::Vec<Real>`
--> src/main.rs:5:6
|
5 | (x[0] + x[1]) * x[2]
| ^^^^ move occurs because value has type `Real`, which does not implement …Run Code Online (Sandbox Code Playgroud)