Skip to content
Related Articles

Related Articles

Improve Article

reflect.SetBool() Function in Golang with Examples

  • Last Updated : 10 May, 2020

Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.SetBool() Function in Golang is used to sets v’s underlying value. To access this function, one needs to imports the reflect package in the program.

Syntax:

func (v Value) SetBool(x bool)

Parameters: This function accept one parameter of bool type (x).

Return Value: This function does not returns any value.

Below examples illustrate the use of the above method in Golang:



Example 1:




// Golang program to illustrate
// reflect.SetBool() Function 
    
package main
    
import (
    "fmt"
    "reflect"
)
    
// Main function
func main() {
      
    typ := reflect.StructOf([]reflect.StructField{
        {
            Name: "Height",
            Type: reflect.TypeOf(bool(true)),
            Tag:  `json:"height"`,
        },
        {
            Name: "Age",
            Type: reflect.TypeOf(int(0)),
            Tag:  `json:"age"`,
        },
    })
  
    v := reflect.New(typ).Elem()
    v.Field(0).SetBool(true)
    fmt.Println(v)
}

Output:

{true 0}

Example 2:




// Golang program to illustrate
// reflect.SetBool() Function 
    
package main
    
import (
    "fmt"
    "reflect"
)
    
type Foo struct {
    A int `tag1:"First Tag" tag2:"Second Tag"`
    B string
    C bool
}
  
func main() {
    greeting := "ABC"
    f := Foo{A: 10, B: "Geek1", C:true}
  
    gVal := reflect.ValueOf(greeting)
    fmt.Println(gVal.Interface())
  
    gpVal := reflect.ValueOf(&greeting)
    gpVal.Elem().SetString("Geek2")
    fmt.Println(greeting)
  
    fType := reflect.TypeOf(f)
    fVal := reflect.New(fType)
    fVal.Elem().Field(0).SetInt(20)
    fVal.Elem().Field(1).SetString("Geeksforgeeks")
    fVal.Elem().Field(2).SetBool(false)
    f2 := fVal.Elem().Interface().(Foo)
    fmt.Printf("%+v, %d, %s, %+v\n", f2, f2.A, f2.B, f2.C)
}

Output:

ABC
Geek2
{A:20 B:Geeksforgeeks C:false}, 20, Geeksforgeeks, false



My Personal Notes arrow_drop_up
Recommended Articles
Page :