On Tue, Sep 17, 2013 at 7:34 AM, Gokcehan Kara <gokcehank...@gmail.com>wrote:
> Hello, > > I have met rust a few days ago and let me pay my respects first for making > such a powerful language. I really hope to succeed making some contribution > in the upcoming days. > > I was reading the tutorial (http://static.rust-lang.org/doc/tutorial.html) > specifically the section 16.3 and I was wondering if there's a rationale > behind making generic bounds explicit. For example in C++ I can do: > > // clang++ asd.cc -std=c++11 -Weverything -Wno-c++98-compat -g && > ./a.out > #include <iostream> > #include <vector> > using namespace std; > > class Klass { > public: > void print() { cout << "printing the thing" << endl; } > }; > > template <typename T> void print_all(vector<T> &things) { > for (auto thing : things) { > thing.print(); > } > } > > int main() { > vector<Klass> v1; > > v1.push_back(Klass()); > v1.push_back(Klass()); > v1.push_back(Klass()); > > print_all(v1); // no errors > > vector<int> v2; > > v2.push_back(1); > v2.push_back(2); > v2.push_back(3); > > print_all(v2); // /tmp/asd.cc:18:10: error: member reference base > type 'int' > // is not a structure or union/tmp/asd.cc:37:3: note: > in > // instantiation of function template specialization > // 'draw_all<int>' requested here > > return 0; > } > > and it gives me the necessary error at compile time. To my limited > knowledge, this is also statically dispatched so should not cause any > overhead. > > I haven't used Haskell much but I know a little bit of Scala. In Scala you > need to be explicit because generics are compiled once to run with > different types. As far as I understand, rust compiles different copies for > each type (monomorphizing?) just like C++ so it might be possible to be > implicit in rust as well. > > Having said that, I'm not sure if being explicit is necessarily a bad > thing. It sure looks good for documenting and I haven't thought of any > cases where it falls short except maybe when a function of the same name is > implemented in different traits. > > Am I failing to see the obvious? > > Thanks in advance, > Gokcehan > In addition to what others have mentioned, explicit bounds allow generics to be type-checked from the definition, rather than each instantiation. You know that *any* set of type parameters fulfilling the bounds listed in the API will compile. It's an enforced minimal level of documentation and results in very clean error messages.
_______________________________________________ Rust-dev mailing list Rust-dev@mozilla.org https://mail.mozilla.org/listinfo/rust-dev