Set Struct Fields With reflect

Write struct fields by name with reflect.Value.FieldByName after CanSet and AssignableTo checks, so generic form or config binding fails with clear errors.

GoForm Validation

Code

snippet
package main

import (
	"fmt"
	"reflect"
)

type Profile struct {
	Name   string
	Age    int
	secret string // 未导出字段:reflect 同样无法 Set
}

// setField 按字段名写入:CanSet 与 AssignableTo 前置检查,失败返回明确错误
func setField(target any, name string, value any) error {
	structVal := reflect.ValueOf(target)
	if structVal.Kind() != reflect.Pointer || structVal.Elem().Kind() != reflect.Struct {
		return fmt.Errorf("need pointer to struct, got %T", target)
	}
	field := structVal.Elem().FieldByName(name)
	if !field.IsValid() {
		return fmt.Errorf("no such field: %s", name)
	}
	if !field.CanSet() {
		return fmt.Errorf("not settable: %s", name)
	}
	assigned := reflect.ValueOf(value)
	if !assigned.Type().AssignableTo(field.Type()) {
		return fmt.Errorf("cannot assign %T to %s %s", value, field.Type(), name)
	}
	field.Set(assigned)
	return nil
}

func main() {
	var p Profile
	fmt.Println(setField(&p, "Name", "alice"))
	fmt.Println(setField(&p, "Age", 30))
	fmt.Println(setField(&p, "secret", "x"))
	fmt.Println(setField(&p, "Missing", true))
	fmt.Println(setField(&p, "Age", "not-a-number"))
	fmt.Printf("loaded: %+v
", p)
}

How it works

Set Struct Fields With reflect reduces to the functions setField and main.

Caveats

  • It stands on its own: no import reaches past what the runtime already provides.

Using it

Signature: func setField(target any, name string, value any) error

main calls 1 helper in sequence: setField.

Key statements

return fmt.Errorf("cannot assign %T to %s %s", value, field.Type(), name)
return fmt.Errorf("need pointer to struct, got %T", target)
return fmt.Errorf("no such field: %s", name)

Interactive Tools for This Topic

FAQ

How do you run Set Struct Fields With reflect?
This is a complete program, not a library excerpt — execution starts at the top.