You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: README.md
+81Lines changed: 81 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -290,6 +290,9 @@ Type manipulation helpers:
290
290
-[CoalesceSliceOrEmpty](#coalescesliceorempty)
291
291
-[CoalesceMap](#coalescemap)
292
292
-[CoalesceMapOrEmpty](#coalescemaporempty)
293
+
-[Cast](#cast)
294
+
= [CastJSON](#castjson)
295
+
-[FromBytes](#frombytes)
293
296
294
297
Function helpers:
295
298
@@ -3431,6 +3434,84 @@ result := lo.CoalesceMapOrEmpty(nil, map[string]int{})
3431
3434
// {}
3432
3435
```
3433
3436
3437
+
### Cast
3438
+
3439
+
Converts any type to a given type. If conversion fails, it returns the zero value of the given type. This is a type-safe version of type assertion.
3440
+
3441
+
Cast enforces strict type assertion, for example trying to convert a number of 10 to float64 will return 0.0 instead of 10.0.
3442
+
3443
+
```go
3444
+
varn any = 10
3445
+
3446
+
fmt.Println(lo.Cast[int](n) == 10) // true
3447
+
3448
+
fmt.Println(lo.Cast[float64](n) == 10.0) // false
3449
+
```
3450
+
3451
+
[[play](https://go.dev/play/p/IxL5n8tOvTW)]
3452
+
3453
+
3454
+
### CastJSON
3455
+
3456
+
Converts any type to a given type based on their json representations. It partially fills the target in case they are not directly compatible. Any errors are ignored.
// Converts any type to a given type. If conversion fails, it returns the zero value of the given type. This is a type-safe version of type assertion.
195
+
//
196
+
// Cast enforces strict type assertion, for example trying to convert a number of 10 to float64 will return 0.0 instead of 10.0.
197
+
funcCast[Tany](valany) T {
198
+
ifval, ok:=val.(T); ok {
199
+
returnval
200
+
}
201
+
varzeroT
202
+
returnzero
203
+
}
204
+
205
+
// Converts any type to a given type based on their json representations. It partially fills the target in case they are not directly compatible. Any errors are ignored.
206
+
funcCastJSON[Tany](valany) T {
207
+
bytes, _:=json.Marshal(val)
208
+
returnFromBytes[T](bytes)
209
+
}
210
+
211
+
// Converts a byte array to a given type. Ignores any errors.
0 commit comments