0

I cannot call Print on a type before change string method that has a String method inside the type's String method:

type book struct{
  id int
  r relateF
  //Or can be delare as r relateF
}
type relateF struct{
  handle int
  grade float64
  name string
}
func(b book) String() string{
  fmt.Println(b)//<=I want to print it before change String method
  return fmt.Sprintf(b.r.name)
}
func main(){
  b1:= book{456,relateF{5,48.2,"History of the world"}}
  fmt.Println(b1)
}

it make a loop

Noname
  • 1
  • 1
  • Related question: https://stackoverflow.com/questions/42600920/runtime-goroutine-stack-exceeds-1000000000-byte-limit-fatal-error-stack-overf – Charlie Tumahai Sep 13 '19 at 04:23

3 Answers3

2

One way is to declare a new temporary type with the same exact structure a book and then convert the book instance to this new type.

func (b book) String() string {
    type temp book       // same structure but no methods
    fmt.Println(temp(b)) // convert book to temp
    return fmt.Sprintf(b.r.name)
}

https://play.golang.com/p/3ebFhptJLxj

mkopriva
  • 35,176
  • 4
  • 57
  • 71
2

You can create a new type based on book that does not override the String() function:

func(b book) String() string{
  type temp book
  fmt.Println(temp(b))
  return fmt.Sprintf(b.r.name)
}
Burak Serdar
  • 46,455
  • 3
  • 40
  • 59
0

This results in recursive calls. When you call Println, it actually calls the String method of the instance. Once you call Println in String, it will inevitably lead to infinite recursion.

If you want to print it before change String method, just comment out String and then print again.

polo xue
  • 104
  • 4