diff options
author | Dan Scales <danscales@google.com> | 2021-02-08 10:23:05 -0800 |
---|---|---|
committer | Dan Scales <danscales@google.com> | 2021-02-08 19:32:55 +0000 |
commit | 0fbde54ea646aa1363fc172610a75e5ba877d4ec (patch) | |
tree | 8248de98dd720fae5b722f6b3f5d0b8b52d7dd71 /test/typeparam/sum.go | |
parent | dcb5e0392e73c900db0f7260b392c91611e33540 (diff) | |
download | go-0fbde54ea646aa1363fc172610a75e5ba877d4ec.tar.gz go-0fbde54ea646aa1363fc172610a75e5ba877d4ec.zip |
[dev.typeparams] cmd/compile: allow generic funcs to call other generic funcs for stenciling
- Handle generic function calling itself or another generic function in
stenciling. This is easy - after it is created, just scan an
instantiated generic function for function instantiations (that may
needed to be stenciled), just like non-generic functions. The types
in the function instantiation will already have been set by the
stenciling.
- Handle OTYPE nodes in subster.node() (allows for generic type
conversions).
- Eliminated some duplicated work in subster.typ().
- Added new test case fact.go that tests a generic function calling
itself, and simple generic type conversions.
- Cause an error if a generic function is to be exported (which we
don't handle yet).
- Fixed some suggested changes in the add.go test case that I missed in
the last review.
Change-Id: I5d61704254c27962f358d5a3d2e0c62a5099f148
Reviewed-on: https://go-review.googlesource.com/c/go/+/290469
Trust: Dan Scales <danscales@google.com>
Trust: Robert Griesemer <gri@golang.org>
Reviewed-by: Robert Griesemer <gri@golang.org>
Diffstat (limited to 'test/typeparam/sum.go')
-rw-r--r-- | test/typeparam/sum.go | 50 |
1 files changed, 50 insertions, 0 deletions
diff --git a/test/typeparam/sum.go b/test/typeparam/sum.go new file mode 100644 index 0000000000..72511c2fe5 --- /dev/null +++ b/test/typeparam/sum.go @@ -0,0 +1,50 @@ +// run -gcflags=-G=3 + +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "fmt" +) + +func sum[T interface{ type int, float64 }](vec []T) T { + var sum T + for _, elt := range vec { + sum = sum + elt + } + return sum +} + +func abs(f float64) float64 { + if f < 0.0 { + return -f + } + return f +} + +func main() { + vec1 := []int{3, 4} + vec2 := []float64{5.8, 9.6} + got := sum[int](vec1) + want := vec1[0] + vec1[1] + if got != want { + panic(fmt.Sprintf("Got %d, want %d", got, want)) + } + got = sum(vec1) + if want != got { + panic(fmt.Sprintf("Got %d, want %d", got, want)) + } + + fwant := vec2[0] + vec2[1] + fgot := sum[float64](vec2) + if abs(fgot - fwant) > 1e-10 { + panic(fmt.Sprintf("Got %f, want %f", fgot, fwant)) + } + fgot = sum(vec2) + if abs(fgot - fwant) > 1e-10 { + panic(fmt.Sprintf("Got %f, want %f", fgot, fwant)) + } +} |