Skip to content

Commit

Permalink
Add type constraints for Map and Array fields (#43)
Browse files Browse the repository at this point in the history
  • Loading branch information
hanzei authored Nov 13, 2023
1 parent e0a61b2 commit bcc267c
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 4 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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: |
Expand Down
4 changes: 2 additions & 2 deletions fieldapi.go
Original file line number Diff line number Diff line change
Expand Up @@ -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}
}
25 changes: 25 additions & 0 deletions fieldapi_test.go
Original file line number Diff line number Diff line change
@@ -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]{})
}
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module github.com/mattermost/logr/v2

go 1.17
go 1.18

require (
github.com/francoispqt/gojay v1.2.13
Expand Down

0 comments on commit bcc267c

Please sign in to comment.