Skip to content

Instantly share code, notes, and snippets.

@tenntenn
Created September 21, 2013 07:15
Show Gist options
  • Save tenntenn/6648064 to your computer and use it in GitHub Desktop.
Save tenntenn/6648064 to your computer and use it in GitHub Desktop.
[Go言語] reflectパッケージで変数の値を変える ref: http://qiita.com/tenntenn/items/3add893529707c837b4f
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)
}
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