Description
While trying to explore how the rust trait system deals with method name collisions 1, I had some difficulty even getting started with simple examples. So I decided to consult rust.md
.
However, transcribing the current examples out of rust.md
and into a new source file does not work "out of the box", because the examples use legacy syntax and cause warnings to be issued 2. When I attempted to fix the transcribed examples to get rid of the warnings, more problems arose.
Partial list of issues in current trait examples:
- The first
trait Shape
example should have explicitself
parameters. - The
draw_twice
example complains due to use of moved value,sh
- The
impl Shape for Circle
example needs an explicit self - The Object types
trait Printable
example needs an exampleself
parameter 3
etc
I argue that it is important to fix these examples, since if the examples are not corrected, it is ambiguous to the reader what format a self parameter is supposed to take. E.g. I initially attempted to correct the problem in this manner (adding a named parameter for the self argument, by analogy with how one puts in names for other method arguments declared on the trait):
trait Shape { fn draw( self, Surface); }
impl Shape for Circle { fn draw(this:self, s: Surface) { do_draw_circle(s, self); } }
but that (obviously?) is not the correct fix, and the compiler complains:
trait-play.rs:29:37: 29:41 error: use of undeclared type name `self`
trait-play.rs:29 impl Shape for Circle { fn draw(this:self, s: Surface) { do_draw_circle(s, self); } }
^~~~
error: aborting due to previous error
(I am aware that the correct fix is to leave the name off of the self
parameter; the point is that the documentation needs to reflect this.)
Footnotes
trait Printable {
fn to_str(self) -> ~str;
}
impl Printable for int {
fn to_str(self) -> ~str { int::to_str(self) }
}
yields:
error: internal compiler error: methods with by-value self should not be called on objects
Footnotes
-
I infer method name collisions to be the motivation for using the syntax
traitname::f()
for static method invocation, and nottypeparameter::f()
; but I wanted to test that name collisions are indeed resolved in some manner. ↩ -
I assume we must be compiling the extracted code samples in some sort of legacy compiler mode? (Maybe these examples should be forcibly tested in a vanilla mode.) Or maybe the issue is that we ignore warnings when compiling the documentation? That should be something one has to opt-into in a written example, though, if possible. ↩
-
Worse, after adding "the obvious"
self
parameter, the code no longer compiles: ↩