Created
September 21, 2013 07:15
-
-
Save tenntenn/6648064 to your computer and use it in GitHub Desktop.
[Go言語] reflectパッケージで変数の値を変える ref: http://qiita.com/tenntenn/items/3add893529707c837b4f
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
package main | |
import ( | |
"fmt" | |
"reflect" | |
) | |
func main() { | |
n := 100 | |
// ダメ | |
nv := reflect.ValueOf(n) | |
fmt.Println(nv.CanSet()) | |
// ポインタを使う | |
npv := reflect.ValueOf(&n) | |
fmt.Println(npv.Elem().CanSet()) | |
npv.Elem().SetInt(200) | |
fmt.Println(n) | |
} |
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
package main | |
import ( | |
"fmt" | |
"reflect" | |
) | |
type Hoge struct { | |
N int | |
} | |
func main() { | |
h := Hoge{10} | |
hpv := reflect.ValueOf(&h) | |
hpv.Elem().FieldByName("N").SetInt(200) | |
fmt.Println(h) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment