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

1

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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)
}

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.