Created
March 2, 2016 14:15
-
-
Save gliush/93a5b91bef7863f33b65 to your computer and use it in GitHub Desktop.
How to make rust work?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Run it with: | |
// echo -e "John Smith\nData1\nData2" > /tmp/in.txt; rustc test.rs && ./test | |
// Then change the output command in the loop in main() and try again | |
use std::io::prelude::*; | |
use std::fs::File; | |
use std::io::{BufReader,Stdout,self}; | |
#[derive(Debug)] | |
pub struct Data<'a>{ | |
name: &'a str, | |
value: String | |
} | |
pub struct Client<IN: BufRead, OUT: Write>{ | |
reader: IN, // file or some tcp connect | |
writer: OUT, // stdout, file or another tcp connect | |
name: Option<String> | |
} | |
impl<IN: BufRead, OUT: Write> Client<IN, OUT> { | |
pub fn read_string(&mut self) -> Option<String> { | |
let mut s = String::new(); | |
if self.reader.read_line(&mut s).unwrap() > 0 { | |
Some(s.trim().to_string()) | |
} else { | |
None | |
} | |
} | |
pub fn read_name(&mut self) { | |
match self.name{ | |
Some(_) => (), | |
None => { self.name = self.read_string() } | |
}; | |
} | |
pub fn read_data<'a>(&'a mut self) -> Option<Data<'a>>{ | |
self.read_name(); | |
match self.read_string() { | |
Some(v) => Some(Data{name: self.name.as_ref().unwrap(), value: v}), | |
None => None | |
} | |
} | |
pub fn write_data(&mut self, data: Data) { | |
self.writer.write_fmt(format_args!("data from {:?}: {:?}", data.name, data.value)); | |
} | |
} | |
pub fn main() { | |
let mut cl = Client{ | |
reader: BufReader::new(File::open("/tmp/in.txt").unwrap()), | |
writer: io::stdout(), | |
name: None | |
}; | |
loop { | |
match cl.read_data() { | |
Some(data) => { | |
// this line works | |
println!("data from {:?}: {:?}", data.name, data.value); | |
// this line doesn't work | |
//cl.write_data(data); | |
() | |
} | |
None => break | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment