github.com/searKing/golang/go@v1.2.117/exp/reflect/struct.go (about) 1 // Copyright 2022 The searKing Author. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package reflect 6 7 import ( 8 "reflect" 9 10 reflect_ "github.com/searKing/golang/go/reflect" 11 ) 12 13 // FieldByNames returns the struct field with the given names. 14 // It returns the zero Value if no field was found. 15 // It panics if v's Kind is not struct or x's Kind is not X. 16 func FieldByNames[V any, X any](v V, names ...string) (x X, ok bool) { 17 val, ok := reflect_.FieldByNames(reflect.ValueOf(v), names...) 18 if ok { 19 return val.Interface().(X), ok 20 } 21 var zero X 22 return zero, false 23 } 24 25 // SetFieldByNames assigns x to the value v. 26 // It panics if CanSet returns false. 27 // As in Go, x's value must be assignable to type of v's son, grandson, etc 28 func SetFieldByNames[V any, X any](v any, names []string, x X) (ok bool) { 29 return reflect_.SetFieldByNames(reflect.ValueOf(v), names, reflect.ValueOf(x)) 30 }