MCPcopy
hub / github.com/expr-lang/expr / get

Function get

builtin/lib.go:546–618  ·  view source on GitHub ↗
(params ...any)

Source from the content-addressed store, hash-verified

544}
545
546func get(params ...any) (out any, err error) {
547 if len(params) < 2 {
548 return nil, fmt.Errorf("invalid number of arguments (expected 2, got %d)", len(params))
549 }
550 from := params[0]
551 i := params[1]
552 v := reflect.ValueOf(from)
553
554 if from == nil {
555 return nil, nil
556 }
557
558 if v.Kind() == reflect.Invalid {
559 panic(fmt.Sprintf("cannot fetch %v from %T", i, from))
560 }
561
562 // Methods can be defined on any type.
563 if v.NumMethod() > 0 {
564 if methodName, ok := i.(string); ok {
565 method := v.MethodByName(methodName)
566 if method.IsValid() {
567 return method.Interface(), nil
568 }
569 }
570 }
571
572 switch v.Kind() {
573 case reflect.Array, reflect.Slice, reflect.String:
574 index := runtime.ToInt(i)
575 l := v.Len()
576 if index < 0 {
577 index = l + index
578 }
579 if 0 <= index && index < l {
580 value := v.Index(index)
581 if value.IsValid() {
582 return value.Interface(), nil
583 }
584 }
585
586 case reflect.Map:
587 var value reflect.Value
588 if i == nil {
589 value = v.MapIndex(reflect.Zero(v.Type().Key()))
590 } else {
591 value = v.MapIndex(reflect.ValueOf(i))
592 }
593 if value.IsValid() {
594 return value.Interface(), nil
595 }
596
597 case reflect.Struct:
598 fieldName := i.(string)
599 value := v.FieldByNameFunc(func(name string) bool {
600 field, _ := v.Type().FieldByName(name)
601 switch field.Tag.Get("expr") {
602 case "-":
603 return false

Callers

nothing calls this directly

Calls 10

ToIntFunction · 0.92
SprintfMethod · 0.80
MethodByNameMethod · 0.80
KeyMethod · 0.80
FieldByNameMethod · 0.80
ErrorfMethod · 0.65
TypeMethod · 0.65
GetMethod · 0.65
LenMethod · 0.45
ZeroMethod · 0.45

Tested by

no test coverage detected