Created
October 7, 2016 06:27
-
-
Save kilfu0701/77c614386483782f68bc5538b6100730 to your computer and use it in GitHub Desktop.
[Golang] Set value into a Struct by string name
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
DEMO: https://play.golang.org/p/DnGeQsaGfi