Skip to content

Instantly share code, notes, and snippets.

@segfo
Last active November 4, 2017 04:02
Show Gist options
  • Save segfo/2e458a12af44a15029795bb37ea56b3e to your computer and use it in GitHub Desktop.
Save segfo/2e458a12af44a15029795bb37ea56b3e to your computer and use it in GitHub Desktop.
newtypeパターンでVec<u8>にDisplayトレイトを実装する
// 既存の型への自作trait以外の実装については
// newtypeパターンでないと実装できないらしい
// いろいろな制約があるとのこと、このあたりは知らん。
use std::fs::File;
use std::io::prelude::*;
use std::fmt;
use std::fmt::Formatter;
// 型を新しく定義する(newtype)
// 構造体で一つの型を包む形になる。(タプル構造体)
struct VecBytes(Vec<u8>);
// VecBytes::new() をとりあえずできるように実装
impl VecBytes{
fn new()->Self{
VecBytes(Vec::<u8>::new())
}
}
// VecBytesをデストラクトすると、Vec<u8>への参照を取り出せるように
// デリファレンス演算子をオーバーロードする。
// 1.イミュータブル
impl std::ops::Deref for VecBytes{
type Target=Vec<u8>;
fn deref(&self) -> &Self::Target{
// self.0 はタプル構造体の最初の要素を表す。
return &self.0;
}
}
// 2.ミュータブル
impl std::ops::DerefMut for VecBytes{
fn deref_mut(&mut self) -> &mut Self::Target{
return &mut self.0;
}
}
fn main(){
let mut file = File::open("src/main.rs").unwrap();
for i in 0..5{
let mut buf = VecBytes::new();
// 参照でやるとmoveが起こらないらしい。わからん。
let s=(&file).take(7).read_to_end(&mut buf).unwrap();
println!("{} / {}",buf,s);
}
}
// 本命のDisplayトレイトを実装
impl std::fmt::Display for VecBytes{
fn fmt(&self, f: &mut Formatter) -> fmt::Result{
write!(f,"Vec<u8> ---> ")?;
for i in &self.0{
write!(f,"{:x} ",i)?;
}
Ok(())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment