You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
When wrapping *regexp.Regexp in a struct, then making an instance of that struct leaving Regexp as nil, calling json.Marshal on the struct will result in a panic.
This did not happen in go 1.20. You can see switch the version on the playground to 1.20 and the program will succeed. The dev branch also has the same problem.
What did you expect to see?
There should not be a panic when invoking json.Marshal on the struct.
What did you see instead?
There was a panic.
The text was updated successfully, but these errors were encountered:
Go 1.21 added a MarshalText method to regexp.Regexp. Since you are embedding it, your struct inherits that method. Consequently, json.Marshal calls it. However, regexp.Regexp.MarshalText panics if the receiver is nil, which normally is fine since json.Marshal wouldn't call it in that case. But here it did because it believes it is calling a method on your struct, which isn't nil.
I'll also note that even without the panic, the 1.20 behavior cannot be restored, because json.Marshal will only consider the inherited MarshalText method and will no longer marshal your struct the usual way. (That is, it will marshal as a string not as an object.)
As there is no way to avoid inheriting a particular method, your only options are to either not embed regexp.Regexp, or explicitly add a MarshalJSON method to your struct.
As an aside, it would be nice if json.Marshal could tell whether MarshalText/MarshalJSON was inherited, since it seems like something that isn't generally intended (or at least you could use `json:"-"` to ignore it).
What version of Go are you using (
go version
)?1.21
Does this issue reproduce with the latest release?
Yes
What operating system and processor architecture are you using (
go env
)?Go playground
What did you do?
Example in playground: https://go.dev/play/p/AfP164Go__e
When wrapping *regexp.Regexp in a struct, then making an instance of that struct leaving Regexp as nil, calling json.Marshal on the struct will result in a panic.
This did not happen in go 1.20. You can see switch the version on the playground to 1.20 and the program will succeed. The dev branch also has the same problem.
What did you expect to see?
There should not be a panic when invoking json.Marshal on the struct.
What did you see instead?
There was a panic.
The text was updated successfully, but these errors were encountered: