From 2ecfb778130c1a2fdd6b4932216e144a0d079d5c Mon Sep 17 00:00:00 2001 From: Romain Marcadier Date: Fri, 24 Nov 2023 19:12:54 +0100 Subject: [PATCH] feat(go): add jsii.Sprintf helper (#4345) It's a fairly common practice to compose string values using `fmt.Sprintf`, however in order to use these with `jsii` they need to be stored into a variable so a pointer can be taken from them, or they need passed into the `jsii.String` function. This new helper removes this constraint and provides a simple way to perform `jsii`-friendly string interpolation. --- By submitting this pull request, I confirm that my contribution is made under the terms of the [Apache 2.0 license]. [Apache 2.0 license]: https://www.apache.org/licenses/LICENSE-2.0 --- packages/@jsii/go-runtime/jsii-runtime-go/helpers.go | 11 ++++++++++- .../@jsii/go-runtime/jsii-runtime-go/helpers_test.go | 4 ++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/packages/@jsii/go-runtime/jsii-runtime-go/helpers.go b/packages/@jsii/go-runtime/jsii-runtime-go/helpers.go index 54f7bc2fce..088e161460 100644 --- a/packages/@jsii/go-runtime/jsii-runtime-go/helpers.go +++ b/packages/@jsii/go-runtime/jsii-runtime-go/helpers.go @@ -1,6 +1,9 @@ package jsii -import "time" +import ( + "fmt" + "time" +) type basicType interface { bool | string | float64 | time.Time @@ -51,6 +54,12 @@ func Numbers[T numberType](v ...T) *[]*float64 { // String returns a pointer to the provided string. func String(v string) *string { return Ptr(v) } +// Sprintf returns a pointer to a fomratted string (semantics are the same as fmt.Sprintf). +func Sprintf(format string, a ...interface{}) *string { + res := fmt.Sprintf(format, a...) + return &res +} + // Strings returns a pointer to a slice of pointers to all of the provided strings. func Strings(v ...string) *[]*string { return PtrSlice(v...) diff --git a/packages/@jsii/go-runtime/jsii-runtime-go/helpers_test.go b/packages/@jsii/go-runtime/jsii-runtime-go/helpers_test.go index 4287dbeda9..edb6cbf0d3 100644 --- a/packages/@jsii/go-runtime/jsii-runtime-go/helpers_test.go +++ b/packages/@jsii/go-runtime/jsii-runtime-go/helpers_test.go @@ -64,6 +64,10 @@ func TestString(t *testing.T) { assert.Equal(t, "Hello", *String("Hello")) } +func TestSprintf(t *testing.T) { + assert.Equal(t, "formatted: 42", *Sprintf("formatted: %d", 42)) +} + func TestStrings(t *testing.T) { assert.Equal(t, []*string{String("Hello"), String("World")}, *Strings("Hello", "World")) }