我想实现Iterator包含可迭代字段的结构的特征。迭代我的结构应该产生与迭代该字段获得的相同结果。这就是我想要的(显然不起作用):
struct Foo {
bar: Vec<char>,
}
impl Iterator for Foo {
type Item: &char; // Error: expected named lifetime parameter
fn next(&mut self) -> Option<Self::Item> {
self.bar.iter().next()
}
}
Run Code Online (Sandbox Code Playgroud)
为了避免该错误,我尝试插入生命周期:
use std::marker::PhantomData;
struct Foo<'a> {
bar: Vec<char>,
phantom: &'a PhantomData<char> // not sure what to put inside < .. >
}
impl<'a> Iterator for Foo<'a> {
type Item = &'a char;
fn next(&mut self) -> Option<Self::Item> {
self.bar.iter().next() // again, several errors about lifetimes
}
}
Run Code Online (Sandbox Code Playgroud)
我如何实现 …
如果我定义A = [1]我得到它A不等于,A'因为它们是不同的类型:
julia> A=[1]
1-element Array{Int64,1}:
1
julia> A'
1×1 LinearAlgebra.Adjoint{Int64,Array{Int64,1}}:
1
julia> A == A'
false
Run Code Online (Sandbox Code Playgroud)
如果我定义另一个向量B = [1, 2, 3]并尝试使用乘积来计算A',A我会得到以下输出:
B=[1,2,3]
3-element Array{Int64,1}:
1
2
3
julia> B*A'
3×1 Array{Int64,2}:
1
2
3
julia> B*A
ERROR: MethodError: no method matching *(::Array{Int64,1}, ::Array{Int64,1})
...
...
Run Code Online (Sandbox Code Playgroud)
这似乎是*运算符签名的问题,Array{Int64,1}在定义C = [4 5]我们得到的另一个向量时,似乎不接受两个作为操作数:
julia> C=[4 5]
1×2 Array{Int64,2}:
4 5
julia> B*C
3×2 Array{Int64,2}: …Run Code Online (Sandbox Code Playgroud) 有没有办法在 Julia 中将向量变量作为命令行参数传递?就我而言,我有两个参数:一个整数和一个整数向量。虽然我可以轻松解析第一个参数,但我没有找到任何令人愉快的方式来解析向量。现在我只是将向量设置为 ,v = parse.(Int, ARGS[2:end])但由于向量的项被视为参数,因此非常令人困惑。是否有一些特殊的语法来处理这种情况?
如何将特征向下转换为结构,就像这个 C# 示例中那样?
我有一个基本特征和几个派生结构,必须将它们推入单个基本特征向量中。
我必须检查向量的每个项目是否可转换为特定的派生结构,如果是,则将其用作该类型的结构。
这是我的 Rust 代码,我不知道如何实现注释部分。
trait Base {
fn base_method(&self);
}
struct Derived1;
impl Derived1 {
pub fn derived1_method(&self) {
println!("Derived1");
}
}
impl Base for Derived1 {
fn base_method(&self) {
println!("Base Derived1");
}
}
struct Derived2;
impl Derived2 {
pub fn derived2_method(&self) {
println!("Derived2");
}
}
impl Base for Derived2 {
fn base_method(&self) {
println!("Base Derived2");
}
}
fn main() {
let mut bases = Vec::<Box<dyn Base>>::new();
let der1 = Derived1{};
let der2 …Run Code Online (Sandbox Code Playgroud)