cast

package
v1.3.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 8, 2021 License: MIT Imports: 4 Imported by: 0

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func DynamicTypeAssertion

func DynamicTypeAssertion(vI interface{}, origin reflect.Value) (reflect.Value, error)

DynamicTypeAssertion - функция для динамического сопоставления типа делает примерно следующее

r := vI.(origin.Type()) - это решило бы все проблемы!!!!
Example
// Назначение: typedVar, err := interfaceVar.(T)

// 1. Представим что в процессе работы, получаем некий слайс вида []interface{}
t := []interface{}{}
for _, v := range []string{"1.1", "2", "3.0", "4"} {
	t = append(t, v)
}

// 2. Хотим восстановить исходный тип
temp := []int{}

r, err := DynamicTypeAssertion(t, reflect.ValueOf(temp))
if err != nil {
	fmt.Printf("can't cast! :(")
	fmt.Println(err)
}
fmt.Printf("Input: %+v %T\nType: %T\nResult: %+v %T\n", t, t, temp, r, r)

// 2. Хотим привести к другому типу
temp1 := []float64{}

r, err = DynamicTypeAssertion(t, reflect.ValueOf(temp1))
if err != nil {
	fmt.Printf("can't cast! :(")
	fmt.Println(err)
}
fmt.Printf("Input: %+v %T\nType: %T\nResult: %+v %T\n", t, t, temp1, r, r)
Output:

func ToFloat64

func ToFloat64(v interface{}) (float64, bool)

ToFloat64 - по возможности приводит интерфейс к типу float64

Example
// If possible cat interface{} to float64

// Here possible type to cast
var sliceI = []interface{}{"1.23", "-1.23", 123, -123, uint(123), int8(1), uint8(1), float32(1.2)} // also int16, int32, int64, uint16, uin32, uin64

for _, v := range sliceI {
	if r, ok := ToFloat64(v); !ok {
		fmt.Println(r) // r - float64
	} else {
		fmt.Println("cant't cast")
	}
}
Output:

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL