Skip to content

Default methods for interfaces #1875

Closed
Closed
@erickt

Description

@erickt

I'm fleshing out the json library to add support for a to_json iface, among other things, and I'm finding a lot of code duplication between my instances. Here's an example:

iface to_json {
    fn to_json_writer(wr: io::writer);
    fn to_json_str() -> str;
}

impl of to_json for float {
    fn to_json_writer(wr: io::writer) {
        wr.write_str(float::to_str(self, 6u));
    }

    fn to_json_str() -> str {
        io::with_str_writer(self.to_json_writer)
    }
}

impl of to_json for int {
    fn to_json_writer(wr: io::writer) {
        wr.write_str(int::str(self));
    }

    fn to_json_str() -> str {
        io::with_str_writer(self.to_json_writer)
    }
}
...

Every implementation's to_json_str is just a straight copy of the others. It would be much nicer if we could provide default versions of functions like to_json_str and just have the implementations inherit it.

iface to_json {
    fn to_json_writer(wr: io::writer);
    fn to_json_str() -> str {
        io::with_str_writer(self.to_json_writer)
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions