11장: 제네릭과 트레이트

Preview

개념 톺아보기

trait

// 예시: std::io::Write

trait Write {
	fn write(&mut self, buf: &[u8]) -> Result<usize>;
	fn flush(&mut self) -> Result<()>;
	fn write_all(&mut self, buf: &[u8]) -> Result<()> { ... }
... }
use std::io::Write;

fn say_hello(out: &mut dyn Write) -> std::io::Result<()> {
    out.write_all(b"hello world\\n")?;
    out.flush()
}
use std::fs::File;

let mut local_file = File::create("hello.txt")?;
say_hello(&mut local_file)?; // works
let mut bytes = vec![];
say_hello(&mut bytes)?; // also works
assert_eq!(bytes, b"hello world\\n");

trait object: dyn