Skip to content

Instantly share code, notes, and snippets.

@kilfu0701
Created October 7, 2016 06:27
Show Gist options
  • Save kilfu0701/77c614386483782f68bc5538b6100730 to your computer and use it in GitHub Desktop.
Save kilfu0701/77c614386483782f68bc5538b6100730 to your computer and use it in GitHub Desktop.
[Golang] Set value into a Struct by string name
// https://play.golang.org/p/DnGeQsaGfi
package main
import (
"fmt"
"reflect"
)
type Ogp struct {
Title string
Description string
Url string
Type string
Image string
Site_name string
}
func setFieldValue(ogp *Ogp, field string, value string) {
r := reflect.ValueOf(ogp)
f := reflect.Indirect(r).FieldByName(field)
if f.Kind() != reflect.Invalid {
f.SetString(value)
}
}
func main() {
o := Ogp{
Title: "qq",
}
fmt.Println(o)
setFieldValue(&o, "Url", "https://www.google.com.tw")
setFieldValue(&o, "Type", "search")
fmt.Println(o)
}
@kilfu0701
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment