The follow sample code will lead to stack overflow because it has the same interface signature as encoding/json/Marshaler.
The json.Marshal(s) will call MarshalJSON internally. So, as a result it turns out to be a recursive function call.
Is that by design? Or a design mistake?
package main
import (
"encoding/json"
"fmt"
)
type IJSON interface {
MarshalJSON() ([]byte, error) // This interface signature is the same as "encoding/json/Marshaler"
}
type Student struct {
Name string `json:"name"`
Age int `json:"age"`
}
func (s *Student) MarshalJSON() ([]byte, error) {
return json.Marshal(s)
}
func main() {
s := &Student{"James", 12}
data, err := s.MarshalJSON()
if err != nil {
panic(err)
}
fmt.Printf("%s", data)
}