How to print struct using the filed's String() method

package main

import (
	"bytes"
	"fmt"
	"reflect"
)
type Email string

type Person struct {
	email Email
	name  string
}

func (e Email) String() string {
	return "super secret!"
}

func main() {
	foo := Person{
		email: "aaa@bbb.com",
		name:  "Bar",
	}
	fmt.Println(foo)
}

expect: {super secret! Bar}, but actually got {aaa@bbb.com Bar}

I also tried using reflect, but seemingly the type information of Email is lost when using Field(i), it only gives the ground type of Email, namly string or reflect.String, so the String() call is not func (e Email) String() string

func StructString(s any) string {
	v := reflect.ValueOf(s)
	t := v.Type()

	if t.Kind() != reflect.Struct {
		panic("todo")
	}

	b := &bytes.Buffer{}
	b.WriteString("{")
	for i := 0; i < v.NumField(); i++ {
		if i > 0 {
			b.WriteString(" ")
		}
		// fileds here
		valField := v.Field(i)
		switch valField.Kind() {
		case reflect.String:
			b.WriteString(valField.String())
		default:
      // inrelavant here...
		}
	}
	b.WriteString("}")
	return b.String()
}

You need to implement the Stringer interface for your struct., Person

1 Like