我有一个叫做的函数add_vec.它需要两个向量并通过对压缩向量中的元素对执行元素加法来创建一个新向量.
extern crate num;
use num::traits::Num;
fn add_vec<N: Num>(v1s: Vec<N>, v2s: Vec<N>) -> Vec<N> {
let mut v3s = Vec::new();
for (v1, v2) in v1s.iter().zip(v2s.iter()) {
v3s.push(v1 + v2)
}
v3s
}
#[cfg(test)]
mod tests {
use super::add_vec;
#[test]
fn it_works() {
let v1s = vec![1, 0, 3];
let v2s = vec![0, 1, 1];
let v3s = add_vec(v1s, v2s);
assert_eq!(v3s, vec![1, 1, 4]);
}
}
Run Code Online (Sandbox Code Playgroud)
问题是我最终得到以下错误消息:
error[E0369]: binary operation `+` cannot be applied to type `&N`
--> src/lib.rs:14:18 …Run Code Online (Sandbox Code Playgroud) 我理解如何操作整个矢量,虽然我不认为这是惯用的Rust:
fn median(v: &Vec<u32>) -> f32 {
let count = v.len();
if count % 2 == 1 {
v[count / 2] as f32
} else {
(v[count / 2] as f32 + v[count / 2 - 1] as f32) / 2.0
}
}
fn main() {
let mut v1 = vec![3, 7, 8, 5, 12, 14, 21, 13, 18];
v1.sort();
println!("{:.*}", 1, median(&v1));
}
Run Code Online (Sandbox Code Playgroud)
但是如果我只想操作这个矢量的一半呢?例如,第一个四分位数是下半部分的中位数,第三个四分位数是上半部分的中位数.我的第一个想法是构建两个新的向量,但这似乎不太正确.
我如何得到"一半"的向量?
我正在ListNode用 Rust编写递归类型。我必须Box在结构中使用,并且我正在尝试编写一个循环来添加next ListNode. 但是,我想尝试使用除递归方法之外的指针。
#[derive(Debug)]
struct ListNode {
val: i32,
next: Option<Box<ListNode>>,
}
impl ListNode {
fn new(i: i32) -> Self {
ListNode { val: i, next: None }
}
fn add_l(&mut self, l: &Vec<i32>) {
let mut p: *mut ListNode = self as *mut ListNode;
for i in l {
unsafe {
(*p).next = Some(Box::new(ListNode::new(*i)));
let temp_b = Box::from_raw(p);
p = Box::into_raw(temp_b.next.wrap());
};
}
}
}
fn main() {
let mut a = …Run Code Online (Sandbox Code Playgroud) 我想创建一个函数来接收一个Vec和一个位置来改变一个数字.
在JavaScript中,这非常简单:
function replaceNumber(line, position, number) {
return [
...line.slice(0, position),
number,
...line.slice(position+1, line.length)
]
}
Run Code Online (Sandbox Code Playgroud)
如何在Rust中创建类似的功能?
我试过这个:
fn replace_number(line: Vec<i32>, point: i32, number: i32) -> Vec<i32> {
return [
&line[0..point as usize],
&[number],
&line[point as usize+1, point.len()]
].concat();
}
Run Code Online (Sandbox Code Playgroud)
结果是一个数组数组.如何像JavaScript示例一样进行解构?
我尝试使用正则表达式从字符串中获取所有非空白字符,但我不断回到相同的错误。
extern crate regex; // 1.0.2
use regex::Regex;
use std::vec::Vec;
pub fn string_split<'a>(s: &'a String) -> Vec<&'a str> {
let mut returnVec = Vec::new();
let re = Regex::new(r"\S+").unwrap();
for cap in re.captures_iter(s) {
returnVec.push(&cap[0]);
}
returnVec
}
pub fn word_n(s: &String, n: i32) -> &str {
let bytes = s.as_bytes();
let mut num = 0;
let mut word_start = 0;
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' || item == b'\n' {
num += 1;
if …Run Code Online (Sandbox Code Playgroud) 我越来越熟悉 Rust 泛型,但我不知道出了什么问题。
use std::collections::BTreeMap;
fn frequency<T: Ord + Clone>(vec: &Vec<T>) -> BTreeMap<T, u32> {
let mut movie_reviews = BTreeMap::new();
let mut vec_ = Vec::new();
vec.push(1);
movie_reviews
}
Run Code Online (Sandbox Code Playgroud)
我不知道为什么它需要 type T:
use std::collections::BTreeMap;
fn frequency<T: Ord + Clone>(vec: &Vec<T>) -> BTreeMap<T, u32> {
let mut movie_reviews = BTreeMap::new();
let mut vec_ = Vec::new();
vec.push(1);
movie_reviews
}
Run Code Online (Sandbox Code Playgroud) 我试图将向量的所有内容连接成一个数字。这就像[1, 2, 4] -> 124。这是我现在所拥有的:
fn sumVector(vec: &Vec<u32>) -> u32 {
return vec.to_owned().concat();
}
Run Code Online (Sandbox Code Playgroud)
这是因错误而失败
fn sumVector(vec: &Vec<u32>) -> u32 {
return vec.to_owned().concat();
}
Run Code Online (Sandbox Code Playgroud) 我是 Rust 和类型系统的新手。我正在阅读rustc/rc.rs。不知道为什么Rc<T>可以调用T的方法。a Structure<T>调用封装值的方法需要满足什么条件?
use std::rc::Rc;
fn main() {
let a = Rc::new("The quick fox".to_string());
println!("{}", a.contains("white")); // Rc<String> can call String#contains.
}
Run Code Online (Sandbox Code Playgroud) 我有一个带有两个参数的函数(假设两个字符串):
fn foo(x: String, y: String) -> String {
x + y
}
Run Code Online (Sandbox Code Playgroud)
我总是x在编译时知道,但y直到运行时我才知道。
我怎样才能编写这个以获得最大效率,而无需为每个函数复制粘贴x?
我有以下代码:
let display_value = entry.path().display();
files_and_dirs.push(DiskEntry {
path: display_value.to_string(),
is_dir: is_dir(display_value.to_string()),
name: display_value.to_string()
});
Run Code Online (Sandbox Code Playgroud)
如果我这样写:
let display_value = entry.path().display();
let dir_name = display_value.to_string();
files_and_dirs.push(DiskEntry {
path: dir_name,
is_dir: is_dir(dir_name),
name: dir_name
});
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
之所以发生移动是因为
dir_name具有typestd::string::String,它没有实现Copy特征
我了解在Rust中,赋值时会四处移动。我想声明一个变量,并在第二个代码块中多次使用它。我该怎么做呢?
rust ×10
generics ×2
borrowing ×1
compile-time ×1
concat ×1
lifetime ×1
regex ×1
type-systems ×1
vector ×1