CodeBlanks Logo Icon CodeBlanks

reflect.Value

Learn the runtime value with Value.

reflect.Value

reflect.ValueOf(v) wraps the value itself. You read its contents with the method that fits the kind: Int(), String(), Float().

v := reflect.ValueOf(7)
fmt.Println(v.Int() * 2)  // 14

Calling the wrong method (e.g. Int() on a string) panics; checking v.Kind() first is safe.

Changing a value: Elem and Set

To change a value through reflect you must pass a pointer; otherwise you work on a copy and Set panics.

x := 1
v := reflect.ValueOf(&x).Elem()
v.SetInt(10)
fmt.Println(x)  // 10

Elem() moves to the value the pointer points to; CanSet() tells whether it is settable.

Practice Change it with reflect

Declare puan := 3. Reach the value with reflect.ValueOf(&puan).Elem(), call SetInt(30) and print puan.

Starter code

main.go
package main

import (
    "fmt"
    "reflect"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "fmt"
    "reflect"
)

func main() {
    puan := 3
    v := reflect.ValueOf(&puan).Elem()
    v.SetInt(30)
    fmt.Println(puan)
}

Expected output

30

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What happens when <code>reflect.ValueOf("Go").Int()</code> runs?

  • It returns 0
  • It returns "Go"
  • It fails to compile
  • It panics Correct answer

Explanation: Int() only works on integer kinds; calling it on a string panics at run time. The compiler can't catch it.

2 Move from pointer to value

Question
n := 5
v := reflect.ValueOf(&n).____()
v.SetInt(8)
Answer
n := 5
v := reflect.ValueOf(&n).Elem()
v.SetInt(8)

Explanation: Elem() gives the value the pointer points to; only then can SetInt be called.

3 Value methods

Term Meaning
Int() Reads an integer
SetInt() Writes an integer
Elem() Follows the pointer
CanSet() Is it settable?

All lessons in Advanced