aceid改为aceld

This commit is contained in:
wandoubaba 2024-11-19 12:27:49 +08:00
parent 9bb9fc04e3
commit 78173a1628
26 changed files with 121 additions and 0 deletions

View File

@ -0,0 +1,63 @@
package main
import (
"fmt"
"reflect"
)
type User struct {
Id int
Name string
Age int
}
func (this *User) Call() {
fmt.Println("user is called...")
fmt.Printf("%v\n", this)
}
func (this User) ThisCall() {
fmt.Println("user is called...")
fmt.Printf("%v\n", this)
}
func reflectNum(arg interface{}) {
fmt.Println("type: ", reflect.TypeOf(arg))
fmt.Println("value: ", reflect.ValueOf(arg))
}
func main() {
var num float64 = 1.2345
reflectNum(num)
user := User{1, "Aceld", 18}
DoFieldAndMethod(user)
}
func DoFieldAndMethod(input interface{}) {
// 获取input的type
inputType := reflect.TypeOf(input)
fmt.Println("inputType is: ", inputType.Name())
// 获取input的value
inputValue := reflect.ValueOf(input)
fmt.Println("inputValue is: ", inputValue)
fmt.Println(inputType.NumMethod())
// 通过type获取里面的字段
// 1. 获取interface的reflect.Type通过Type得到NumField进行遍历
// 2. 得到每个field数据类型
// 3. 通过field有一个Interface()方法得到对应的value
// for i := 0; i < inputType.NumField(); i++ {
// field := inputType.Field(i)
// value := inputValue.Field(i).Interface()
// fmt.Printf("%s: %v = %v\n", field.Name, field.Type, value)
// }
// 通过type获取里面的方法调用
for i := 0; i < inputType.NumMethod(); i++ {
m := inputType.Method(i)
fmt.Printf("%s: %v\n", m.Name, m.Type)
}
}

View File

@ -0,0 +1,58 @@
package main
import (
"fmt"
"reflect"
)
type User struct {
Name string
Sex string
Age int
secret string
}
func (this *User) PointerCall() {
fmt.Println("*User is called ...")
fmt.Printf("%v\n", this)
}
func (this User) Call() {
fmt.Println("User is called ...")
fmt.Printf("%v\n", this)
}
func main() {
user := User{"Aaron", "male", 18, "my secrets"}
GetFieldsAndMethods(user)
}
func GetFieldsAndMethods(input interface{}) {
inputType := reflect.TypeOf(input)
inputValue := reflect.ValueOf(input)
fmt.Println("inputType: ", inputType.Name())
fmt.Println("inputValue: ", inputValue)
numField := inputType.NumField()
numMethod := inputType.NumMethod()
fmt.Println("numField: ", numField)
fmt.Println("numMethod: ", numMethod)
// 遍历属性并打印键值
for i := 0; i < inputType.NumField(); i++ {
field := inputType.Field(i)
fmt.Println(field.PkgPath)
// PkgPath is the package path that qualifies a lower case (unexported)
// field name. It is empty for upper case (exported) field names.
// See https://golang.org/ref/spec#Uniqueness_of_identifiers
if field.PkgPath == "" {
value := inputValue.Field(i).Interface()
fmt.Printf("%s: %v = %v\n", field.Name, field.Type, value)
} else {
fmt.Printf("%s: %v = <unexported>\n", field.Name, field.Type)
}
}
// 遍历方法并打印
for i := 0; i < inputType.NumMethod(); i++ {
m := inputType.Method(i)
fmt.Printf("%s: %v\n", m.Name, m.Type)
}
}