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.
Code
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
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- How do you run Set Struct Fields With reflect?
- This is a complete program, not a library excerpt — execution starts at the top.
Report a problem with this exampleOpens a pre-filled issue on GitHub.