What you want is primarily reflection methods. The values ββare called NumFields() int and Field(int) . The only thing you are missing is a string check and the SetString method.
package main import "fmt" import "reflect" import "strings" type MyStruct struct { A,B,C string I int D string J int } func main() { ms := MyStruct{"Green ", " Eggs", " and ", 2, " Ham ", 15}
(link on the playground)
There are two caveats here:
You need a pointer to what you are about to change. If you have a value, you need to return the modified result.
Attempts to change unexposed fields usually lead to panic. If you plan to modify the outstanding fields, be sure to do this trick inside the package.
This code is quite flexible, you can use switch statements or type switches (according to the value returned by the .Interface () field) if you need different behavior depending on the type.
Change Regarding tag behavior, you seem to already understand this. When you have a field and checked that it is a string, you can simply use field.Tag.Get("max") and field.Tag.Get("max") it there.
Edit2: I made a small mistake in the tag. Tags are part of reflection. The type of structure, so to get them you can use (this is a little long) msValue.Type().Field(i).Tag.Get("max")
( version of the playground code published in the comments using the working tag).
source share