El lenguaje Go proporciona una implementación de soporte incorporada de la reflexión en tiempo de ejecución y permite que un programa manipule objetos con tipos arbitrarios con la ayuda del paquete de reflexión. La función reflect.SetBool() en Golang se usa para establecer el valor subyacente de v. Para acceder a esta función, es necesario importar el paquete reflect en el programa.
Sintaxis:
func (v Value) SetBool(x bool)Parámetros: Esta función acepta un parámetro de tipo bool (x).
Valor devuelto: esta función no devuelve ningún valor.
Los siguientes ejemplos ilustran el uso del método anterior en Golang:
Ejemplo 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) }
Producción:
{true 0}
Ejemplo 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) }
Producción:
ABC Geek2 {A:20 B:Geeksforgeeks C:false}, 20, Geeksforgeeks, false
Publicación traducida automáticamente
Artículo escrito por SHUBHAMSINGH10 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA