gogofmt

Define string output for type in Golang


I'm wondering if there's a way through fmt to specify the way a string would get outputted for specific types. For example, I have a token struct that contains a bunch of information on the token, like token type (which is an int, but for clarity reasons, it would make more sense if I could output the name of the token type as a string).

So when I print a specific type of variable, is there a straightforward way to specify/implement the string output of such a type?

If that doesn't really make sense, Rust has an excellent form of doing so (from their doc)

use std::fmt;

struct Point {
    x: i32,
    y: i32,
}

impl fmt::Display for Point {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "({}, {})", self.x, self.y)
    }
}

let origin = Point { x: 0, y: 0 };

println!("The origin is: {}", origin); // prints "The origin is: (0, 0)"

Solution

  • You need to implement the interface Stringer, like this:

    import "fmt"
    
    type Point struct {
        x int
        y int
    }
    
    func (p Point) String() string {
        return fmt.Sprintf("(%d, %d)", p.x, p.y)
    }
    
    func main() {
        fmt.Println(Point{1, 2})
    }
    

    (Go Playground)

    In Go you don't specify which interfaces a type implements, you just implements the required methods.