我根据参数创建了一些端口,但是端口不能长时间传递到下一个函数,任何生命周期都要完成?更好的是,这是一种适应静态调度的方法吗?
public class NoInternetConnection extends Fragment {
Common_Tasks commonTasks;
public NoInternetConnection() {
}
@Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_nointernet, container, false);
commonTasks = new Common_Tasks(getActivity());
}
答案 0 :(得分:1)
您可以直接在每个匹配组中调用run
函数来使用静态调度:
use std::fs::File;
use std::io::{Read, Write};
fn init(i: Option<&str>, o: Option<&str>) {
match i {
Some(filename) => init2(File::open(filename).expect("Couldn't open input file."), o),
None => init2(std::io::stdin(), o),
}
}
fn init2<R: Read>(i: R, o: Option<&str>) {
match o {
Some(filename) => run(i, File::create(filename).expect("Couldn't open output file")),
None => run(i, std::io::stdout()),
}
}
fn run<R: Read, W: Write>(i: R, o: W) {
unimplemented!()
}
答案 1 :(得分:1)
最简单的解决方案是Box
您的对象,将它们放入堆中。
我个人更愿意将init
和run
分开,所以这意味着要归还它们:
fn init(matches: Matches) -> (Box<Read>, Box<Write>) {
let in_port: Box<Read> = match matches.opt_str("i") {
Some(filename) => Box::new(File::open(filename).expect("Couldn't open input file.")),
_ => Box::new(stdin()),
};
let out_port: Box<Write> = match matches.opt_str("o") {
Some(filename) => Box::new(File::create(filename).expect("Couln't open output file")),
_ => Box::new(stdout()),
};
(in_port, out_port)
}
答案 2 :(得分:1)
问题在于你是否试图返回对你即将销毁的东西的引用:
let in_port: &mut Read = match matches.opt_str("i") {
Some(filename) => &mut File::open(filename).expect("Couldn't open input file.") as &mut Read,
_ => &mut io::stdin() as &mut Read,
};
在块中,创建的File
是一个临时的,它只会持续它所表达的表达式。我假设您使用的是引用而不是值,这样您就可以隐藏特质对象背后的具体类型。一种方式是我们Box<Trait>
,它将拥有该对象。
fn init<'a>(i: Option<&str>, o: Option<&str>) {
let mut in_port: Box<Read> = match i {
Some(filename) => Box::new(File::open(filename).expect("Couldn't open input file.")),
_ => Box::new(io::stdin()),
};
let mut out_port: Box<Write> = match o {
Some(filename) => Box::new(File::create(filename).expect("Couln't open output file")),
_ => Box::new(io::stdout()),
};
run(&mut in_port, &mut out_port);
}