Skip to content

fix: Use value receiver for MarshalJSON#4211

Open
alexandear wants to merge 2 commits into
google:masterfrom
alexandear-org:change/marshal-value-receiver
Open

fix: Use value receiver for MarshalJSON#4211
alexandear wants to merge 2 commits into
google:masterfrom
alexandear-org:change/marshal-value-receiver

Conversation

@alexandear
Copy link
Copy Markdown
Contributor

Consistently use value receivers for MarshalJSON methods.

The issue is clearly illustrated by the following program, where panic is never called. However, if we change p := Person{"Bob"} to p := &Person{"Bob"}, everything works as expected, and the panic occurs.

package main

import (
	"encoding/json"
	"fmt"
)

type Person struct {
	Name string
}

func (p *Person) MarshalJSON() ([]byte, error) {
	panic("unexpected")
}

func main() {
	p := Person{"Bob"}
	b, err := json.Marshal(p)
	if err != nil {
		panic(err)
	}
	fmt.Printf("%s\n", b)
}

The issue exists only in encoding/json v1. The experimental encoding/json/v2 package does not have this issue.

See https://go.dev/issue/22967 for more details.

I think this is a non-breaking change.

@gmlewis gmlewis added the NeedsReview PR is awaiting a review before merging. label May 13, 2026
@codecov
Copy link
Copy Markdown

codecov Bot commented May 13, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.69%. Comparing base (a5eca73) to head (7c033db).

Additional details and impacted files
@@           Coverage Diff           @@
##           master    #4211   +/-   ##
=======================================
  Coverage   93.69%   93.69%           
=======================================
  Files         209      209           
  Lines       19772    19772           
=======================================
  Hits        18526    18526           
  Misses       1049     1049           
  Partials      197      197           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

NeedsReview PR is awaiting a review before merging.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants