@ -25,10 +25,8 @@ func Set[K comparable, V any, T ~map[K]V](m *T, k K, v V) {
// (currently only a slice or a map) and makes sure it's non-nil for
// JSON serialization. (In particular, JavaScript clients usually want
// the field to be defined after they decode the JSON.)
// MakeNonNil takes a pointer to a Go data structure
// (currently only a slice or a map) and makes sure it's non-nil for
// JSON serialization. (In particular, JavaScript clients usually want
// the field to be defined after they decode the JSON.)
//
// Deprecated: use NonNilSliceForJSON or NonNilMapForJSON instead.
func NonNil ( ptr interface { } ) {
if ptr == nil {
panic ( "nil interface" )
@ -51,3 +49,23 @@ func NonNil(ptr interface{}) {
rv . Set ( reflect . MakeMap ( rv . Type ( ) ) )
}
}
// NonNilSliceForJSON makes sure that *slicePtr is non-nil so it will
// won't be omitted from JSON serialization and possibly confuse JavaScript
// clients expecting it to be preesnt.
func NonNilSliceForJSON [ T any , S ~ [ ] T ] ( slicePtr * S ) {
if * slicePtr != nil {
return
}
* slicePtr = make ( [ ] T , 0 )
}
// NonNilMapForJSON makes sure that *slicePtr is non-nil so it will
// won't be omitted from JSON serialization and possibly confuse JavaScript
// clients expecting it to be preesnt.
func NonNilMapForJSON [ K comparable , V any , M ~ map [ K ] V ] ( mapPtr * M ) {
if * mapPtr != nil {
return
}
* mapPtr = make ( M )
}