Skip to content

std::fmt needs documentation on how to implement the traits #9865

Closed
@chris-morgan

Description

@chris-morgan

OK, so we have our fancy new formatting with its traits and all, but at present it's not obvious as (most commonly) a library developer how to implement its goodness for your own types.

We should have a new section in the std::fmt documentation on "how to implement these traits". I think the general advice should be to use write!. It could have an example like this:

use std::fmt;

struct Vector2D {
    x: int,
    y: int,
}

impl fmt::Default for Vector2D {
    fn fmt(obj: &Vector2D, f: &mut fmt::Formatter) {
        write!(f.buf, "({}, {})", obj.x, obj.y)
    }
}

(I still hate the way it's a static method with an explicit first argument rather than a regular method with &self. But ah! there is no syntax to express the other at present.)

This is a very basic example; more will be needed for the adventurous, covering flags, padding and so forth, how f.buf is a Writer which means you're dealing a lot with bytes rather than strings, etc.

This is related to #9806 in that it will make the way toward removing ToStr plainer.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions