反射
reflect包只有interface 才有反射这一说
interface 类型的变量包含2个指针
一个指针指向值的类型,一个指针指向实际的值
ValueOf 用来获取数据的值
TypeOf 用来获取值的类型
通过反射修改值
// 获取域名对应的ip
    host, err := net.Dial("ip:icmp", "video_video")
    if err != nil {
        fmt.Println(err)
        return
    }
    ip := host.RemoteAddr()
    fmt.Println("---", ip.String())
    
    //这下面才是使用反射修改值
    var link string =""
    sqlLink := reflect.ValueOf(&link)
    newSqlLink :=sqlLink.Elem()
    newSqlLink.SetString(fmt.Sprintf("root:root@tcp(%s:3309)/video_video?charset=utf8&parseTime=True&loc=Local",ip.String()))
    fmt.Println(newSqlLink)
sqlLink := reflect.ValueOf(&link) 必须是指针类型,才能修改。(切片 map类型除外) newSqlLink :=sqlLink.Elem() 获取指针对象的值 newSqlLink.SetString() 修改成字符串的,有很多Set类型的函数。 newSqlLink.CanSet() 判断是否可以修改
通过反射调用函数或方法
思路 step1: 接口变量->对象放射对象:Value step2:获取对应的方法对象:MethodByName() step3: 将方法对象进行调用:Call()
反射调用函数
package main
import (
    "fmt"
    "reflect"
)
type Person struct {
    Name string
    Age int
    Sex string
}
func (p *Person)PrintInfo()  {
    fmt.Println("----")
}
func (p *Person)Say(i int)  {
    fmt.Println("----",i)
}
func main() {
    p1 := Person{"Ruvb",20,"nan"}
    value := reflect.ValueOf(&p1)
    fmt.Printf("kind:%s,type :%s \n",value.Kind(),value.Type())
    //无参数的方法
    methondValue := value.MethodByName("PrintInfo")
    fmt.Printf("kind:%s,type :%s \n",methondValue.Kind(),methondValue.Type())
    //反射调用
    methondValue.Call(nil) // 没有参数传入空切片
    arg1 := make([]reflect.Value,0) // 没有参数传入空切片
    methondValue.Call(arg1)
    //有参数的方法
    methondValue2 := value.MethodByName("Say")
    fmt.Printf("kind:%s,type :%s \n",methondValue2.Kind(),methondValue2.Type())
    //反射调用
    //methondValue2.Call(123123 ) // 没有参数传入空切片
    arg2 := []reflect.Value{reflect.ValueOf(123)} // 没有参数传入空切片
    methondValue2.Call(arg2)
}
反射调用函数
package main
import (
    "fmt"
    "reflect"
)
func fun1()  {
    fmt.Printf("fun1:无参数")
}
func fun2( i int){
    fmt.Printf("fun2:有参数 %d",i)
}
func fun3( i int , str string) (b int){
    b = 666
    fmt.Printf("fun3:有参数 %d , %s 有返回值 %d \n",i,str,b)
    return b
}
func main() {
    f1:=fun1
    f2:=fun2
    f3:=fun3
    value1 := reflect.ValueOf(f1)
    value2 := reflect.ValueOf(f2)
    value3 := reflect.ValueOf(f3)
    fmt.Printf("kind:%s,type :%s \n",value1.Kind(),value1.Type())
    fmt.Printf("kind:%s,type :%s \n",value2.Kind(),value2.Type())
    fmt.Printf("kind:%s,type :%s \n",value3.Kind(),value3.Type())
    value1.Call(nil)
    value2.Call([]reflect.Value{reflect.ValueOf(123)})
    mm := value3.Call([]reflect.Value{reflect.ValueOf(123),reflect.ValueOf("你好")})
    fmt.Printf("kind:%s,type :%s \n",mm[0].Kind(),mm[0].Type())
    fmt.Println(mm[0].Interface().(int))
}