The Stringer Interface Link to heading

If you call fmt.Print with a value that implements the Stringer interface, then print will call the String method. This allows you to provide a custom format for your types.



package main

import "fmt"

type Document struct {
	content string
}

func (d *Document) String() string {
	return "content:" + d.content
}

func NewDocument(content string) *Document {
	return &Document{
		content: content,
	}
}

func main() {
	var doc *Document = NewDocument("Hello World")

	if doc.String() == fmt.Sprint(doc) {
		fmt.Println("Great we expected to be here.")
	}
}

Weird Print Behavior Link to heading

All pretty straight forward right?

Based on the code snippet below can you guess what will be printed?

	var doc2 *ConfusedDocument = NewConfusedDocument("hello world")
	if doc2.String() == fmt.Sprint(doc2) {
		fmt.Println("we should be here. Right??")
	} else {
		fmt.Println("Why are we here??")
	}

You might be surprised! Test the code snippet above here.. Link to heading

The implementation of ConfusedDocument is at the bottom of the code snippet so you can take a swing at debugging the code before you see the answer at the bottom.