Reputation: 1
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
Upvotes: 0
Views: 37
Reputation: 104
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.
Upvotes: 0
Reputation: 51577
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)
}
Upvotes: 2
Reputation: 38223
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
Upvotes: 2