當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Golang reflect.SetBool()用法及代碼示例

Go語言提供了運行時反射的內置支持實現,並允許程序借助反射包來操縱任意類型的對象。 Golang中的reflect.SetBool()函數用於設置v的基礎值。要訪問此函數,需要在程序中導入反射包。

用法:
func (v Value) SetBool(x bool)

參數:此函數接受布爾類型(x)的一個參數。

返回值:該函數不返回任何值。

以下示例說明了以上方法在Golang中的用法:



範例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) 
}

輸出:

{true 0}

範例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) 
}

輸出:

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



相關用法


注:本文由純淨天空篩選整理自SHUBHAMSINGH10大神的英文原創作品 reflect.SetBool() Function in Golang with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。