Created
August 9, 2017 14:09
-
-
Save segfo/24e96262ae5ee35d709227065d7bec17 to your computer and use it in GitHub Desktop.
トレイトで抽象化
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
use std::io::{BufReader,BufWriter,BufRead,Read,Write}; | |
use std::net::{TcpListener, TcpStream}; | |
use std::fs::File; | |
use std::io::prelude::*; | |
// WriteトレイトとReadトレイトを実装しているSugoiTraitを実装すると | |
trait SugoiTrait:Write+Read{ | |
} | |
// TCPストリームも | |
impl SugoiTrait for std::net::TcpStream{ | |
} | |
// ファイルも | |
impl SugoiTrait for File{ | |
} | |
// 全部一個の関数で処理できる | |
fn sugoiHoge(suggo_i:&mut SugoiTrait){ | |
println!("WriteトレイトとReadトレイトを継承したオブジェクトを引数に取れるよ!"); | |
println!("ファイルもネットワークも抽象化!"); | |
println!("すごーい!"); | |
} | |
fn main() { | |
let mut file = File::open("foo.txt").unwrap(); | |
let mut stream = TcpStream::connect("127.0.0.1:34254").unwrap(); | |
println!("Hello, world!"); | |
sugoiHoge(&mut stream); | |
sugoiHoge(&mut file); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment