Skip to content

Instantly share code, notes, and snippets.

@mesuutt
Created May 19, 2021 21:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mesuutt/316651e1d7fc5e10132d77a974a04444 to your computer and use it in GitHub Desktop.
Save mesuutt/316651e1d7fc5e10132d77a974a04444 to your computer and use it in GitHub Desktop.

Traits

Trait bound:

trait bound fonksiyon tanimi(static dispatch):

fn foo<T: MyTrait>(f: &T) {}

Static type dispach yapar. foo(inek), foo(koyun) gibi cagirdigimizda compile time'da iki ayri fn generate edilir.

Alttaki struct da trait bound, hep ayni tip'i alir(T): Vektorun 1. elemani inek ise hepsi inek, koyunsa hepsi koyun olmak zorunda.

struct Village<T: MyTrait> {
	animals: Vec<T>
}

let animals = vec![Dog {}, Dog {}]; // hepsi ayni tipte olan objeler iceren bir vector. Sadece kopek var.
let village2 = Village {
    animals
};

for i in village2.animals {
    println!("{}", i.speak());
}

Biz bu struct icerisinde hem inek, hem koyunlari tutmak istiyorsak nasil yapicaz peki? Burda dynamic dispatch edilen trait objeler isin icine giriyor: Cunku biz vector'un her bir elemaninin boyunu compile time'da bilmiyoruz. (foo = Vec) diyemiyoruz cunku herzaman inek gelmeyebilir,

Trait object:

MyTrait'i implement eden iki farkli objeyi icerebilein(hem kopek, hem ordek) bir vector'de donuyor ve trait methodunu cagiriyoruz.

struct Village<T: MyTrait> {
	animals: Vec<Box<T>>
}

// Struct icerisinde dynamic dispatch
// vec olustururken tipini vermezsek calismiyor cunku vec default olarak icindeki degerin tipini
// 1. elemanin tipi olarak kabul ediyor.
let animals: Vec<Box<dyn MyTrait>> = vec![Box::new(Dog {}), Box::new(Dog {}), Box::new(Duck {})];
let village = Village {
    animals
};

for i in village.animals {
    println!("{}", i.speak());
}

Burda gordugumuz gibi Box icerisine aldik cunku Box'in compile time'da size'i belli.

dynamic dispatch fonksiyon tanimi:

fn foo(f: &dyn MyTrait) {}

kod icerisinde foo(inek) veya foo(koyun) diye cagirsak bile her iki struct icin compile time'da fn generate edilmez, sadece bu iki obje gercekten trait'i implement ediyor mu kontrolu yapilir ama runtime'da vtable uzerinden fonksiyon bulunup cagrilir.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment