github.com/blend/go-sdk@v1.20220411.3/reflectutil/try_assignment.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package reflectutil
     9  
    10  import "reflect"
    11  
    12  func tryAssignment(field, value reflect.Value) (assigned bool, err error) {
    13  	if value.Type().AssignableTo(field.Type()) {
    14  		field.Set(value)
    15  		assigned = true
    16  		return
    17  	}
    18  
    19  	if value.Type().ConvertibleTo(field.Type()) {
    20  		convertedValue := value.Convert(field.Type())
    21  		if convertedValue.Type().AssignableTo(field.Type()) {
    22  			field.Set(convertedValue)
    23  			assigned = true
    24  			return
    25  		}
    26  	}
    27  
    28  	if field.Type().Kind() == reflect.Ptr {
    29  		if value.Type().AssignableTo(field.Type().Elem()) {
    30  			elem := reflect.New(field.Type().Elem())
    31  			elem.Elem().Set(value)
    32  			field.Set(elem)
    33  			assigned = true
    34  			return
    35  		} else if value.Type().ConvertibleTo(field.Type().Elem()) {
    36  			elem := reflect.New(field.Type().Elem())
    37  			elem.Elem().Set(value.Convert(field.Type().Elem()))
    38  			field.Set(elem)
    39  			assigned = true
    40  			return
    41  		}
    42  	}
    43  
    44  	return
    45  }