在Rust中切换输入源的最佳方法

时间:2016-09-15 12:01:35

标签: pattern-matching rust lifetime dispatch

我根据参数创建了一些端口,但是端口不能长时间传递到下一个函数,任何生命周期都要完成?更好的是,这是一种适应静态调度的方法吗?

    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());

}

3 个答案:

答案 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您的对象,将它们放入堆中。

我个人更愿意将initrun分开,所以这意味着要归还它们:

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);
}

playground