Go語言學習筆記 reflection

2021-08-07 03:22:25 字數 2060 閱讀 2581

學習筆記根據 無聞

go語言基礎教程 整理

package main

import (

"fmt"

"reflect"

)type user struct

type manager struct

func set(o inte***ce{}) else

f := v.fieldbyname("name")

if !f.isvalid()

if f.kind() == reflect.string

}func (u user) hello()

func (u user) sayhello(name string)

func info(o inte***ce{})

v := reflect.valueof(o)

fmt.println("fields:")

for i:= 0

; i < t.numfield(); i++

/**// for迴圈輸出

fields:

id: int = 1

name: string = ok

age: int = 12

*/fmt.println("********************")

for i:=0

; i m := t.method(i)

fmt.printf("%6s: %v\n", m.name, m.type)

}/**

// 列印出的結果:

hello: func(main.user)

*/}func main()

func test1()

info(u)

// info(&u) // 如果傳入這樣的值,就會終止執行

}// 測試匿名字段

func test2() , title:"123"}

t := reflect.typeof(m)

fmt.printf("%#v\n", t.field(0))

fmt.println("***************==")

fmt.printf("%#v\n", t.field(1))

fmt.println("-----------------")

fmt.printf("%#v\n", t.fieldbyindex(int)) // 通過傳遞進去的slice,來取匿名字段

fmt.println()

fmt.printf("%#v\n", t.fieldbyindex(int)) // 通過傳遞進去的slice,來取匿名字段

fmt.println()

/*列印出的結果:*/

/* reflect.structfield, anonymous:true}

***************==

reflect.structfield, anonymous:false}

-----------------

reflect.structfield, anonymous:false}

reflect.structfield, anonymous:false}

*/}// 使用reflect 修改基本型別的值

func test3()

// 通過反射對介面物件中的值進行修改

func test4()

set(&u)

fmt.println(u) //

}// 直接呼叫修改方法

func test5()

u.sayhello("john") // hello john , my name is ok

}// 通過reflect來呼叫方法

func test6()

v := reflect.valueof(u)

mv := v.methodbyname("sayhello")

args := reflect.value

mv.call(args) // hello john , my name is ok

}

GO語言學習 反射reflect

反射能在執行期探知物件的型別資訊和記憶體結構。也是實現元程式設計的重要手段。反射所需的全部資訊都源自介面變數。介面變數處儲存自身型別外,還會儲存實際物件的型別資料。將任何傳入的物件轉換為介面型別 func typeof i inte ce type func valueof i inte ce va...

go語言學習筆記

type info struct func main fmt.println info1 data,json.marshal info1 fmt.println string data 輸出 這裡要特別注意的是 json 冒號後面和雙引號之間千萬不要有空格!被坑慘了 go語言 import的包的前面...

Go語言 學習筆記

import 下劃線 如 import hello imp 的作用 當匯入乙個包時,該包下的檔案裡所有init 函式都會被執行,然而,有些時候我們並不需要把整個包都匯入進來,僅僅是是希望它執行init 函式而已。這個時候就可以使用 import 引用該包。即使用 import 包路徑 只是引用該包,...