虽然向量最适合程序编程,但我想map在它们上使用函数.以下代码段有效:
fn map<A, B>(u: &Vec<A>, f: &Fn(&A) -> B) -> Vec<B> {
let mut res: Vec<B> = Vec::with_capacity(u.len());
for x in u.iter() {
res.push(f(x));
}
res
}
fn f(x: &i32) -> i32 {
*x + 1
}
fn main() {
let u = vec![1, 2, 3];
let v = map(&u, &f);
println!("{} {} {}", v[0], v[1], v[2]);
}
Run Code Online (Sandbox Code Playgroud)
为什么标准库中没有这样的功能?(以及std::collections::LinkedList).有没有其他方法来处理它?
我想在Rust中创建一个非二叉树结构.这是一个尝试
struct TreeNode<T> {
tag : T,
father : Weak<TreeNode<T>>,
childrenlists : [Rc<TreeNode<T>>]
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,这不编译.
main.rs:4:1: 8:2 error: the trait `core::marker::Sized` is not implemented for the type `[alloc::rc::Rc<TreeNode<T>>]` [E0277]
main.rs:4 struct TreeNode<T> {
main.rs:5 tag : T,
main.rs:6 father : Weak<TreeNode<T>>,
main.rs:7 childrenlist : [Rc<TreeNode<T>>]
main.rs:8 }
main.rs:4:1: 8:2 note: `[alloc::rc::Rc<TreeNode<T>>]` does not have a constant size known at compile-time
main.rs:4 struct TreeNode<T> {
main.rs:5 tag : T,
main.rs:6 father : Weak<TreeNode<T>>,
main.rs:7 childrenlist : [Rc<TreeNode<T>>]
main.rs:8 }
error: aborting …Run Code Online (Sandbox Code Playgroud) 通过Rust的文档,我只看到了以下方法
fn push_all(&mut self, other: &[T])
Run Code Online (Sandbox Code Playgroud)
将多个值推送到已存在的值Vec.但是,如果我有一个迭代器,我认为它使用效率不高:vector.push_all(it.collect().as_ref()).有办法实现吗?
我有一个a类型的变量&[T]; 我怎样才能获得对子片段的引用a?
作为一个具体的例子,我想得到第一和第二部分a,提供a.len()是偶数.
我的问题如下,但我想问一下标题中稍微宽泛的问题.
我有一个a类型为Chars其他字符串的迭代器.假设我在读取字符串时发现错误,并且我想打印错误消息.这条消息应该提到错误在字符串中的位置(行号等).在Rust标准库中有什么方法可以帮助我吗?
如何在Haskell中定义宏常量?特别是,我想在没有第二个模式匹配的情况下运行以下代码片段重叠.
someconstant :: Int
someconstant = 3
f :: Int -> IO ()
f someconstant = putStrLn "Arg is 3"
f _ = putStrLn "Arg is not 3"
Run Code Online (Sandbox Code Playgroud)