- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想分支并决定在运行时在函数内使用的 Trait 实现(参见下面代码示例中的 poly_read
)。 trait 对象是在 if 表达式的分支臂内部构造的,只需要在 poly_read
的生命周期内存在,但我需要 Box
它,因为 trait 不能从表达式臂中借用,直到我试图将其分配给的绑定(bind)。
我从逻辑上理解为什么借用过早结束,但当 if 表达式的值被绑定(bind)时,借用检查器似乎应该能够将借用扩展到周围的范围。我意识到这可能是一个幼稚的想法,但我想更多地了解为什么这是不可能的。
我对现在的解决方案有点不满意,因为它需要堆分配,尽管我觉得我不应该需要一个,因为我只在函数的生命周期内保留该框。我想这是因为我们不知道在采用分支之前堆栈上所需的 reader
的大小,但它不能只在编译器中表示为联合,因为我们至少知道最大尺寸。
顺便说一句,我实际上并不知道我对堆分配的 Box
的担忧从一开始就有多大意义。一般装箱的值(value)是多少?
#![feature(io)]
#![feature(path)]
const BYTES: &'static [u8] = &[1u8, 2, 3, 4, 5];
const PATH: &'static str = "/usr/share/dict/words";
use std::old_io::{File, Reader, BufReader};
fn read(r: &mut Reader) {
let some_bytes = r.read_exact(5).unwrap();
assert!(some_bytes.len() == 5);
println!("{:?}", some_bytes);
}
fn poly_read(from_file: bool) {
// Is there any way to extend the lifetime of the ``&mut Reader`` in these branch arms without
// boxing them as I'm doing now. It seems wasteful to do a heap allocation when the actual
// borrow only needs to happen for body of poly_read?
let mut reader = if from_file {
Box::new(File::open(&Path::new(PATH)).unwrap()) as Box<Reader>
// Would like to say:
// File::open(&Path::new(FILE)).unwrap() as &mut Reader
} else {
Box::new(BufReader::new(BYTES)) as Box<Reader>
// Would like to say:
// BufReader::new(BYTES) as &mut Reader
};
// It feels like I'd like the lifetime of values returned from if expressions to be of the
// surrounding scope, rather than the branch arms.
read(&mut reader);
}
fn main() {
poly_read(true);
poly_read(false);
}
最佳答案
正如@Shepmaster 所指出的,有一种类似于 this answer 的方法可以做到这一点来自previous question .
解决这个问题的方法是预先声明两个必要的变量:一个File
和一个BufReader
:
fn poly_read(from_file: bool) {
// These two variables are predeclared so that they are in scope as
// long as `reader` is
let mut file_reader;
let mut buf_reader;
let mut reader = if from_file {
file_reader = File::open(&Path::new(PATH)).unwrap();
&mut file_reader as &mut Reader
} else {
buf_reader = BufReader::new(BYTES);
&mut buf_reader as &mut Reader
};
read(&mut reader);
}
关于rust - 我可以在运行时选择特征对象而不使用 Box<Trait> 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28264349/
我正在尝试在具有相同特征的盒装特征对象上实现特征。我以前对其方法采用的特征做过这样的事情&Self,它工作得很好,但不是Self。。我意识到在这个特定的例子中,我可以将fn get_*()函数更改为返
在编写带有特征的代码时,您可以将特征放在特征边界中: use std::fmt::Debug; fn myfunction1(v: Box) { println!("{:?}", v); }
我有一个特征正在使用另一个特征,现在我收到关于类中不存在的函数的错误。我简化了代码: 设置.php: getMessage());} } } ?> 数据库.php pdo=new PDO("m
这个问题在这里已经有了答案: Why doesn't Rust support trait object upcasting? (4 个回答) 2年前关闭。 如果我有 Box , 我可以返回 &dyn
给定这段代码: trait Trait {} struct Child; impl Trait for Child {} struct Father { child: &'a Box, } i
这个问题的标题与许多相关问题非常相似,但我还没有找到一个讨论这个特定问题的问题。 我有一个 Color非常简单定义的类型,如下所示: pub struct Color { red: u8,
我有三个特点。 Trait Param、GroupId 和 SessionId。特征 GroupId 和 SessionId 包括 Param。 类 GroupSession 包括特征 GroupId
查看 Traversable 和 TraversableLike 的 scaladoc,我很难弄清楚它们之间的区别是什么(除了一个扩展另一个)。文档中唯一明显的区别是它说 Traversable 是一
我有以下代码: trait T { type AT; fn foo(&self); } struct AbstractT { t: Box>, } impl T for Abs
如何在 Rust 中尝试类似以下的操作? builder 类是一个 trait 对象,它返回另一个 trait 对象(类型删除),其中选择的实现由我们正在使用的 builder trait 的特定对象
我想创建一个新向量,其中包含实现 Trait 的对象,来 self 已有的包含这些对象的一些向量。 trait Foo { // } struct Bar { i: i32, } st
到目前为止,在我的项目中,我使用了许多特征来允许在单元测试中模拟/ stub 以注入(inject)依赖项。然而,到目前为止我正在做的事情的一个细节似乎非常可疑,以至于我很惊讶它甚至可以编译。我担心正
假设我有一些特质: trait MyTrait { fn function1(&self); } 和一些实现它的类型: struct MyStruct { number: i32, }
更新:不止我一个人在思考这个问题,看来这确实是一个错误。参见 here .修复的那一天将是美好的一天! :) 这开始为 I love PHP traits! I'm going to use them
以下特征Parser[+T]是扩展接受 Input 的函数的特征并返回 Result[T] . trait Parser[+T] extends (Input => Result[T]) 那是对的吗
我有一个类型,我可以通过它访问它的方法 SomeTrait::::method() 但我不明白那和之间的区别 >::method() 在 C++ 中,我希望这样: SomeTrait::method(
在下面的代码中,不可能从对实现相同特征的动态大小类型的引用中获得对特征对象的引用。为什么会这样呢?如果我可以同时调用trait方法,那么&dyn Trait和&(?Sized + Trait)之间到底
我是 Rust 的新手,我想通过实现一些小项目来学习这门语言并更好地理解。我的第一次尝试是解析从 MQTT 代理收到的 JSON 数据。 我很高兴在 tornado 的帮助下轻松完成这项工作。和 se
在下面的代码中,不可能从对实现相同特征的动态大小类型的引用中获得对特征对象的引用。为什么会这样呢?如果我可以同时调用trait方法,那么&dyn Trait和&(?Sized + Trait)之间到底
这个问题在这里已经有了答案: Why is the `Sized` bound necessary in this trait? (2 个回答) 1年前关闭。 我有一个特质 Vertex我想要几个结构
我是一名优秀的程序员,十分优秀!