From bcc267c2de5155b1921515c7e5d9781153b5218f Mon Sep 17 00:00:00 2001 From: Ben Schumacher Date: Mon, 13 Nov 2023 14:28:27 +0100 Subject: [PATCH] Add type constraints for Map and Array fields (#43) --- .github/workflows/test.yml | 2 +- fieldapi.go | 4 ++-- fieldapi_test.go | 25 +++++++++++++++++++++++++ go.mod | 2 +- 4 files changed, 29 insertions(+), 4 deletions(-) create mode 100644 fieldapi_test.go diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index d72f56d..094cf64 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -22,7 +22,7 @@ jobs: - name: Install Go uses: actions/setup-go@v2 with: - go-version: 1.17.x + go-version: 1.18.x - name: Add dependencies run: | diff --git a/fieldapi.go b/fieldapi.go index 58b1228..d230035 100644 --- a/fieldapi.go +++ b/fieldapi.go @@ -100,11 +100,11 @@ func Millis(key string, val int64) Field { } // Array constructs a field containing a key and array value. -func Array(key string, val interface{}) Field { +func Array[S ~[]E, E any](key string, val S) Field { return Field{Key: key, Type: ArrayType, Interface: val} } // Map constructs a field containing a key and map value. -func Map(key string, val interface{}) Field { +func Map[M ~map[K]V, K comparable, V any](key string, val M) Field { return Field{Key: key, Type: MapType, Interface: val} } diff --git a/fieldapi_test.go b/fieldapi_test.go new file mode 100644 index 0000000..177c860 --- /dev/null +++ b/fieldapi_test.go @@ -0,0 +1,25 @@ +package logr + +import "testing" + +func TestFieldArray(t *testing.T) { + Array("array", []string{}) + Array("array", []any{}) + + type myArray []any + Array("array", myArray{}) + + type myGenericArray[T any] []T + Array("array", myGenericArray[any]{}) +} + +func TestFieldMap(t *testing.T) { + Map("array", map[string]any{}) + Map("array", map[int]any{}) + + type myMap map[string]string + Map("array", myMap{}) + + type myGenericMap[K comparable, V any] map[K]V + Map("array", myGenericMap[int, any]{}) +} diff --git a/go.mod b/go.mod index f5c0fde..ea4e0c0 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/mattermost/logr/v2 -go 1.17 +go 1.18 require ( github.com/francoispqt/gojay v1.2.13