[rust-dev] Why do we have 'closed' objects?

Rafael Ávila de Espíndola respindola at mozilla.com
Tue Jan 4 12:25:36 PST 2011

While working on a patch I noticed that I had to write things like


instead of just the_vec.len() or len(the_vec). I don't expect us to 
change this before getting a bootstrap compiler, but I decided to write 
this so that we don't forget.

Having to type "_vec." is a small inconvenience since the type is 
present in many lines if I then decide to switch to another structure.

More interesting maybe is if I want to write a generic function 
total_length that sums the length of every element in a vector. How 
would that be done in rust? Something like

fn total_length[t](vec[t] v) -> int {
   auto total = 0u;
   for (e in v) {
     total += e.len();
   ret total;

I suppose. But then, how do I pass a vector of vectors of integers? I 
would have to create a wrapper like

obj vec_with_length(vec[int] x) {
	fn len() -> uint {
		ret _vec.len(x);

Might not look like a big issue, but it involves creating a new object 
which unless I am mistaken can have exactly the same representation as 
the original one.

Since, unlike java or c++, in rust we need a vtable per implemented 
interface, there wouldn't be much to be lost by dropping the requirement 
that all functions in the vtable be declared in one place.

One way to do this is something like go where methods are declared out 
of objects:

obj foo(int state);
method bar(foo @this) {...}

auto x = foo(4)
x.bar()... // or bar(x), but that looks a bit more confusing to me.

and a user can then easily declare a 'zed' method that can be used where 
it would normally be in context:

import ...foo;

mod x {
	method zed(foo @this) {...}
	auto y = foo();
	y.zed(); // OK

	auto y = foo();
	y.zed(); // not OK, no method zed found.



More information about the Rust-dev mailing list