Monday, May 20, 2024
HomeGolangprint struct utilizing the filed's String() methodology - Getting Assist

print struct utilizing the filed’s String() methodology – Getting Assist


package deal foremost

import (
	"bytes"
	"fmt"
	"replicate"
)
kind Electronic mail string

kind Individual struct {
	electronic mail Electronic mail
	title  string
}

func (e Electronic mail) String() string {
	return "tremendous secret!"
}

func foremost() {
	foo := Individual{
		electronic mail: "aaa@bbb.com",
		title:  "Bar",
	}
	fmt.Println(foo)
}

anticipate: {tremendous secret! Bar}, however truly acquired {aaa@bbb.com Bar}

I additionally tried utilizing replicate, however seemingly the kind data of Electronic mail is misplaced when utilizing Subject(i), it solely offers the bottom kind of Electronic mail, namly string or replicate.String, so the String() name will not be func (e Electronic mail) String() string

func StructString(s any) string {
	v := replicate.ValueOf(s)
	t := v.Kind()

	if t.Sort() != replicate.Struct {
		panic("todo")
	}

	b := &bytes.Buffer{}
	b.WriteString("{")
	for i := 0; i < v.NumField(); i++ {
		if i > 0 {
			b.WriteString(" ")
		}
		// fileds right here
		valField := v.Subject(i)
		change valField.Sort() {
		case replicate.String:
			b.WriteString(valField.String())
		default:
      // inrelavant right here...
		}
	}
	b.WriteString("}")
	return b.String()
}

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments