为什么都是&[u8]和&[u8; 3]确定在这个例子吗?
fn main() {
let x: &[u8] = &[1u8, 2, 3];
println!("{:?}", x);
let y: &[u8; 3] = &[1u8, 2, 3];
println!("{:?}", y);
}
Run Code Online (Sandbox Code Playgroud)
&[T; n]可以胁迫的事实&[T]是使它们可以容忍的方面. - 克里斯摩根
为什么可以&[T; n]胁迫&[T]?在其他条件下,这种强制发生了吗?
是否有任何直接的方法在线性时间内&[T]和/或Vec<T>中间或开始处插入或替换多个元素Vec?
我只能找到std::vec::Vec::insert,但这只是为了O(n)及时插入一个元素,所以我显然无法在循环中调用它.
我可以split_off在那个指数上做一个extend新的元素进入左半部分,然后extend是下半部分进入第一个,但有更好的方法吗?
以下内容仅用作示例,而不是有效的Rust代码.
struct Vec<T: Sized, Count> {
a: [T; Count]
}
Run Code Online (Sandbox Code Playgroud)
在C++模板中可能有类似的东西,但我还没有在Rust中看到它.
我想创建这样的数组:
let arr = [0; length];
Run Code Online (Sandbox Code Playgroud)
长度是a usize.但是我得到了这个错误
E0307
The length of an array is part of its type. For this reason, this length
must be a compile-time constant.
Run Code Online (Sandbox Code Playgroud)
是否可以创建动态长度的数组?我想要一个数组,而不是一个数组Vec.
我想调用.map()一系列枚举:
enum Foo {
Value(i32),
Nothing,
}
fn main() {
let bar = [1, 2, 3];
let foos = bar.iter().map(|x| Foo::Value(*x)).collect::<[Foo; 3]>();
}
Run Code Online (Sandbox Code Playgroud)
但编译器抱怨:
error[E0277]: the trait bound `[Foo; 3]: std::iter::FromIterator<Foo>` is not satisfied
--> src/main.rs:8:51
|
8 | let foos = bar.iter().map(|x| Foo::Value(*x)).collect::<[Foo; 3]>();
| ^^^^^^^ a collection of type `[Foo; 3]` cannot be built from an iterator over elements of type `Foo`
|
= help: the trait `std::iter::FromIterator<Foo>` is not implemented for `[Foo; 3]`
Run Code Online (Sandbox Code Playgroud)
我该怎么做呢?
我拥有一个3号数组的所有权,我想迭代它,随着我的去向移动元素.基本上,我想IntoIterator实现一个固定大小的数组.
由于数组没有在标准库中实现这个特性(我理解为什么),是否有解决方法来获得所需的效果?我的对象不是Copy也不是Clone.我可以Vec从数组中创建一个然后迭代进入Vec,但我甚至不确定如何做到这一点.
(有关信息,我想完成一系列的Complete)
这是一个简单的情况示例(天真的iter()尝试):
// No-copy, No-clone struct
#[derive(Debug)]
struct Foo;
// A method that needs an owned Foo
fn bar(foo: Foo) {
println!("{:?}", foo);
}
fn main() {
let v: [Foo; 3] = [Foo, Foo, Foo];
for a in v.iter() {
bar(*a);
}
}
Run Code Online (Sandbox Code Playgroud)
给
error[E0507]: cannot move out of borrowed content
--> src/main.rs:14:13
|
14 | bar(*a);
| ^^ cannot move out of …Run Code Online (Sandbox Code Playgroud) 我想在 Rust 中创建一个包含 10 个空向量的数组,但[Vec::new(); 10]由于Vec没有实现Copy. 我怎样才能做到这一点,更一般地说,我怎样才能通过重复调用一个函数来初始化一个数组?
Rust提供了一些在用户定义的结构中存储元素集合的方法.可以为结构提供自定义生存期说明符和对切片的引用:
struct Foo<'a> {
elements: &'a [i32]
}
impl<'a> Foo<'a> {
fn new(elements: &'a [i32]) -> Foo<'a> {
Foo { elements: elements }
}
}
Run Code Online (Sandbox Code Playgroud)
或者可以给它一个Vec对象:
struct Bar {
elements: Vec<i32>
}
impl Bar {
fn new(elements: Vec<i32>) -> Bar {
Bar { elements: elements }
}
}
Run Code Online (Sandbox Code Playgroud)
这两种方法有哪些主要区别?
Vec每当我打电话时,会使用强制语言来复制内存Bar::new(vec![1, 2, 3, 4, 5])吗?Vec当所有者Bar超出范围时,是否会隐含销毁内容?可能重复:
如何使用PHP解析和处理HTML?
$content = "
<p>This is the first paragraph</p>
<p>This is the second paragraph</p>
<p>This is the third paragraph</p>";
Run Code Online (Sandbox Code Playgroud)
给定上面的一串html内容,我需要在第N段标记之后插入.
我如何解析内容并插入给定的文本字符串,在第2段之后说"你好世界"?