GoCollections/lang/Lang.go

65 lines
941 B
Go
Raw Normal View History

2022-11-25 18:19:33 +08:00
/*
* Copyright (c) 2022 tursom. All rights reserved.
* Use of this source code is governed by a GPL-3
* license that can be found in the LICENSE file.
*/
2022-03-21 11:02:41 +08:00
package lang
2022-11-26 13:42:30 +08:00
import (
2022-11-27 18:34:18 +08:00
"reflect"
2022-11-26 13:42:30 +08:00
"unsafe"
)
2022-11-27 18:34:18 +08:00
func TypeName[T any]() string {
t := reflect.TypeOf(Nil[T]())
return t.Name()
}
func TypeNameOf(v any) string {
t := reflect.TypeOf(v)
return t.Name()
}
2022-03-21 11:02:41 +08:00
func Nil[T any]() T {
var n T
return n
}
2022-03-23 10:15:18 +08:00
func Len[T any](array []T) int {
return len(array)
}
func Append[T any](slice []T, elems ...T) []T {
return append(slice, elems...)
}
2022-03-28 18:19:05 +08:00
func TryCast[T any](v any) (T, bool) {
if v == nil {
return Nil[T](), true
} else {
t, ok := v.(T)
return t, ok
}
}
func Cast[T any](v any) T {
if v == nil {
return Nil[T]()
} else {
2022-11-27 18:34:18 +08:00
t, ok := v.(T)
if !ok {
panic(NewTypeCastException2[T](v, nil))
}
return t
2022-03-28 18:19:05 +08:00
}
}
2022-04-02 15:25:35 +08:00
func ForceCast[T any](v unsafe.Pointer) *T {
2022-03-28 18:19:05 +08:00
if v == nil {
2022-04-02 15:25:35 +08:00
return nil
2022-03-28 18:19:05 +08:00
} else {
2022-04-02 15:25:35 +08:00
return (*T)(v)
2022-03-28 18:19:05 +08:00
}
}