Skip to content

Commit ccaa907

Browse files
committed
go/analysis/passes/unmarshal: allow unmarshalling to a type parameter
We can also unmarshal data to a type parameter, in addition to a pointer and an interface. This analyzer probably requires more discussion, but this solution should be sufficient for now. Updates golang/go#48704 Change-Id: I333f919109295e80a04e59df131713553cdbe612 Reviewed-on: https://go-review.googlesource.com/c/tools/+/353210 Run-TryBot: Rebecca Stambler <[email protected]> Trust: Rebecca Stambler <[email protected]> TryBot-Result: Go Bot <[email protected]> Reviewed-by: Robert Findley <[email protected]> gopls-CI: kokoro <[email protected]>
1 parent 0ebff1a commit ccaa907

File tree

3 files changed

+30
-2
lines changed

3 files changed

+30
-2
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package typeparams
2+
3+
import (
4+
"encoding/json"
5+
"fmt"
6+
)
7+
8+
func unmarshalT[T any](data []byte) T {
9+
var x T
10+
json.Unmarshal(data, x)
11+
return x
12+
}
13+
14+
func unmarshalT2[T any](data []byte, t T) {
15+
json.Unmarshal(data, t)
16+
}
17+
18+
func main() {
19+
x := make(map[string]interface{})
20+
unmarshalT2([]byte(`{"a":1}`), &x)
21+
fmt.Println(x)
22+
}

go/analysis/passes/unmarshal/unmarshal.go

+2-1
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import (
1414
"golang.org/x/tools/go/analysis/passes/inspect"
1515
"golang.org/x/tools/go/ast/inspector"
1616
"golang.org/x/tools/go/types/typeutil"
17+
"golang.org/x/tools/internal/typeparams"
1718
)
1819

1920
const Doc = `report passing non-pointer or non-interface values to unmarshal
@@ -85,7 +86,7 @@ func run(pass *analysis.Pass) (interface{}, error) {
8586

8687
t := pass.TypesInfo.Types[call.Args[argidx]].Type
8788
switch t.Underlying().(type) {
88-
case *types.Pointer, *types.Interface:
89+
case *types.Pointer, *types.Interface, *typeparams.TypeParam:
8990
return
9091
}
9192

go/analysis/passes/unmarshal/unmarshal_test.go

+6-1
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,14 @@ import (
99

1010
"golang.org/x/tools/go/analysis/analysistest"
1111
"golang.org/x/tools/go/analysis/passes/unmarshal"
12+
"golang.org/x/tools/internal/typeparams"
1213
)
1314

1415
func Test(t *testing.T) {
1516
testdata := analysistest.TestData()
16-
analysistest.Run(t, testdata, unmarshal.Analyzer, "a")
17+
tests := []string{"a"}
18+
if typeparams.Enabled {
19+
tests = append(tests, "typeparams")
20+
}
21+
analysistest.Run(t, testdata, unmarshal.Analyzer, tests...)
1722
}

0 commit comments

Comments
 (0)