From 7bd89359c97735394639f091e263a66ba69eecc8 Mon Sep 17 00:00:00 2001 From: Josh Bleecher Snyder Date: Fri, 4 Sep 2020 15:19:12 -0700 Subject: [PATCH] cmd/cloner: generate a package-level Clone function This Clone function knows how to clone any types for which it has generated Clone methods. This allows callers to efficiently clone an inbound interface{} that might contain one of these types. Signed-off-by: Josh Bleecher Snyder --- cmd/cloner/cloner.go | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/cmd/cloner/cloner.go b/cmd/cloner/cloner.go index c8f09fdc5..098faaca1 100644 --- a/cmd/cloner/cloner.go +++ b/cmd/cloner/cloner.go @@ -95,6 +95,29 @@ func main() { } } + w := func(format string, args ...interface{}) { + fmt.Fprintf(buf, format+"\n", args...) + } + w("// Clone duplicates src into dst and reports whether it succeeded.") + w("// To succeed, must be of types <*T, *T> or <*T, **T>,") + w("// where T is one of %s.", *flagTypes) + w("func Clone(dst, src interface{}) bool {") + w(" switch src := src.(type) {") + for _, typeName := range typeNames { + w(" case *%s:", typeName) + w(" switch dst := dst.(type) {") + w(" case *%s:", typeName) + w(" *dst = *src.Clone()") + w(" return true") + w(" case **%s:", typeName) + w(" *dst = src.Clone()") + w(" return true") + w(" }") + } + w(" }") + w(" return false") + w("}") + contents := new(bytes.Buffer) fmt.Fprintf(contents, header, *flagTypes, pkg.Name) fmt.Fprintf(contents, "import (\n")