github.com/tursom/GoCollections@v0.3.10/lang/Lang.go (about)

     1  /*
     2   * Copyright (c) 2022 tursom. All rights reserved.
     3   * Use of this source code is governed by a GPL-3
     4   * license that can be found in the LICENSE file.
     5   */
     6  
     7  package lang
     8  
     9  import (
    10  	"reflect"
    11  )
    12  
    13  func TypeName[T any]() string {
    14  	t := reflect.TypeOf(Nil[T]())
    15  	return t.Name()
    16  }
    17  
    18  func TypeNameOf(v any) string {
    19  	t := reflect.TypeOf(v)
    20  	return t.Name()
    21  }
    22  
    23  func Nil[T any]() T {
    24  	var n T
    25  	return n
    26  }
    27  
    28  func Len[T any](array []T) int {
    29  	return len(array)
    30  }
    31  
    32  func Append[T any](slice []T, elems ...T) []T {
    33  	return append(slice, elems...)
    34  }
    35  
    36  func TryCast[T any](v any) (T, bool) {
    37  	if v == nil {
    38  		return Nil[T](), true
    39  	} else {
    40  		t, ok := v.(T)
    41  		return t, ok
    42  	}
    43  }
    44  
    45  func Cast[T any](v any) T {
    46  	if v == nil {
    47  		return Nil[T]()
    48  	} else {
    49  		t, ok := v.(T)
    50  		if !ok {
    51  			panic(NewTypeCastException2[T](v, nil))
    52  		}
    53  		return t
    54  	}
    55  }