Skip to content

Commit

Permalink
feat(go): add jsii.Sprintf helper (#4345)
Browse files Browse the repository at this point in the history
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
  • Loading branch information
RomainMuller committed Nov 24, 2023
1 parent b7c0f7f commit 2ecfb77
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
11 changes: 10 additions & 1 deletion packages/@jsii/go-runtime/jsii-runtime-go/helpers.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package jsii

import "time"
import (
"fmt"
"time"
)

type basicType interface {
bool | string | float64 | time.Time
Expand Down Expand Up @@ -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...)
Expand Down
4 changes: 4 additions & 0 deletions packages/@jsii/go-runtime/jsii-runtime-go/helpers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"))
}
Expand Down

0 comments on commit 2ecfb77

Please sign in to comment.