1

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)"
Brian Leishman
  • 8,155
  • 11
  • 57
  • 93

1 Answers1

3

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.

bereal
  • 32,519
  • 6
  • 58
  • 104
  • 1
    There is also the [fmt.Formatter interface](https://golang.org/pkg/fmt/#Formatter) for more precise control. – Peter Oct 28 '18 at 19:59