You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Currently, the only way to dynamically access the fields in a struct is through reflection. Having a simple way to range over structs as if they were map[string]anys would enable various struct idioms to be used more often.
See below for some examples of such idioms:
typevarsstruct {
EditorstringShellstringPidint
}
funcExampleGetFields() {
env:=vars{
Editor: "vim",
Shell: "/bin/dash",
Pid: 100,
}
forname, val:=rangestructs.Fields(env) {
name:=strings.ToUpper(name)
val:=fmt.Sprint(val) // val is a string/int because env was passed by valueos.Setenv(name, val)
}
fmt.Println(os.Environ())
//Output:// [... EDITOR=vim SHELL=/bin/dash PID=100 ...]
}
funcExampleSetFields() {
varenvvarsforname, val:=rangestructs.Fields(&env) {
name:=strings.ToUpper(name)
switchval:=val.(type) { // val is a *string/*int because &env was passedcase*string:
*val=os.Getenv(name)
case*int:
*val, _=strconv.Atoi(os.Getenv(name))
}
}
fmt.Printf("%#v\n", env)
//Output:// {Editor:"nano", Shell:"/bin/bash", Pid:2499}
}
funcExampleStringKeys() {
varenvvars
{
envMap:=maps.Collect(structs.Fields(&env))
*envMap["Editor"].(*string) ="code"*envMap["Shell"].(*string) ="/bin/zsh"pidKey:="P"+strings.ToLower("ID")
*envMap[pidKey].(*int) =42
}
fmt.Printf("%#v\n", env)
//Output:// {Editor:"code", Shell:"/bin/zsh", Pid:42}
}
Proposal Details
Currently, the only way to dynamically access the fields in a struct is through reflection. Having a simple way to
range
over structs as if they weremap[string]any
s would enable various struct idioms to be used more often.See below for some examples of such idioms:
Sample implementation (may contain errors):
The text was updated successfully, but these errors were encountered: