Chapter IV Go language interface and reflection

First, the interface

  definition

  Interface defines an object's code of conduct to regulate the development is not achieved, the need to achieve a specific target specification details

// definition of the interface 
type interface {// the name of the interface defining an interface 
    Talk () 
    Eat. () Returns an int type int // 
    the Run () 
}

  Implementation of the interface

  As long as an object method comprising interface, then that implements this interface, the interface type variable can hold Examples of specific types of

type Animal interface{
    Talk()
    Eat()
    Name() string
}
type Dog struct{
}
func (d Dog) Talk(){
    fmt.Println("汪汪")
}
func (d Dog) Eat(){
    fmt.Println("吃骨头")
}
func (d Dog) Name() string{
    fmt.Println("旺财")
    return "旺财"
}
func test(){
    var b Dog
    var a Animal
    a = b
    a.Name()
    a,Eat()
    a.Talk()
}

  Interface calls sort sort

type Student struct {
    Name string
    Id   string
    Age  int
}
type StudentArray []Student
func (p StudentArray) Len() int {
    return len(p)
}
func (p StudentArray) Less(i, j int) bool {
    return p[i].Name > p[j].Name
}
func (p StudentArray) Swap(i,j int) {
    p[i],p[j] = p[j],p[i]
}
func test(){
    var stus StudentArray
    for i := 0;i<10;i++{
        stu := Student{
            Name : fmt.Sprintf("stu%d",rand.Intn(100)),
            Id : fmt.Sprintf("110%d",rand.Intn()),
            Age : randIntn(100),
        }
        = append heat (heat, STU) 
    } 
    for _ V: = {heat range 
        fmt.Println, (v) 
    } 
    fmt.Println ( "\ n \ n") 
    sort.Sort (or not) 
    for _, v = range or not; { 
        fmt.Println, (v) 
    } 
}

  Air Interface

  Empty interface does not define any method, so any type can be realized empty interface

func test(){
    var a interface{}
    var b int = 100
    a = b
    fmt.Printlf(%T %v\n",a,a)    //int 100
    var c string = "hi"
    a = c
    fmt.Printf("%T %v\n",a,a)    //string hi
    var d map[string]int = make(map[string]int,10)
    d["abc"] = 100
    d["aaa"] = 30
    a = d
    fmt.Printf("%T %v\n",a,a)    //map[string]int map[abc:100 aaa:30]
}

func Descrtribe(a interface{}){
    fmt.Printf("type = %T %v\n",a,a)
}
type Student struct{
    Name string
    Sex int
}
func test2(){
    a := 99
    describe(a)    //type=int 99
    b := "hello"
    describe(b)    //type = string hello
    var stu Student = Student{
        Name:"user01",
        Sex:1,
    }
    describe(stu)    //type = main.Student {user01 1}
}

  Type assertion

  Obtaining specific values ​​stored inside the interface type

// OK statement evaluates 
FUNC DESCRIBE (interface {A}) { 
    S, ok: A = (int). 
    IF ok ok {// syntax used, to prevent the introduction being given the wrong type 
        fmt.Println (S) 
        return 
    } 
    STR, ok : A = (String). 
    IF OK { 
        fmt.Println (STR) 
        return 
    } 
    F, OK: A = (float32). 
    IF OK { 
        fmt.Println (F) 
        return 
    } 
    fmt.Println ( "input error") 
    return 
} 
Test FUNC () { 
    var int = 100 A 
    DESCRIBE (A) 
    var B String = "Hi" 
    DESCRIBE (B) 
} 

// Sitch-type statement to determine  
func testSwitch (a interface {}) {
    switch v: = a (type) {.
    case stirng:L
        fmt.Printf("a is string,value:%v\n",v)
    case int:
        fmt.Printf("a is int,value:%v\n", v)
    case float32:
        fmt.Printf("a is float32,value:%v\n", v)
    default:
        fmt.Println("not support type\n")
    }
}
func test2(){
    var a int = 100
    testSwitch(a)
    var b string = "Parallel"
    testSAwitch(b)
}

  Receiving the pointer value and the difference between the reception

  Interface type pointer type variable values ​​achieved can be stored, an interface pointer type variable value type can not be deposited to achieve

// be the same cash can implement multiple interfaces 
type interface Animal { 
    Talk () 
} 
type interface {Bu 
    Bu () 
} 
type Dog struct { 
} 
FUNC (D Dog) Talk () { 
    fmt.Println ( "bark") 
} 
FUNC (D dog) Bu () { 
    fmt.Println (* mammalian dog ") 
} 
FUNC Test () { 
    var D dog 
    var Animal A 
    A = D 
    a.Talk () 
    var Bu B 
    B = D   
    b.Bu () 
}

  Interface list

type LinkNode struct{
    data interface{}
    next *LinkNode
}
type Link struct {
    head *LinkNode
    tail *LikNode
}
func (p *Link) InsertHead(data interface{}) {
    node := &LinkNode{
        data : data,
        next : nil,
    }
    if p.taiil == nil && p.head == nil{
        p.tail = node
        p.head = node
        return
    }
    node.next = p.head
    p.head = node
}
func (p *Link) InsertTail(data interfdace{}) {
    node := &LinkNode{
        data : data,
        next : nil,
    }
    if p.tail == nil && p.head{
        p.tail = node
        p.head = node
        reutrn
    }
    p.tail.next = node
    p.tail = node
}
func (p *Link) Trans(){
    q := p.head
    if q != nil {
        fmt.Println(q.data)
        q = q.next
    }
}
func main(){
    var intLink Link
    for i := 0;i<10;i++{
        intLink.InsertHead(i)
        intLink.InsertTail(i)
    }
    intLink.Trans()
}

  Nesting Interface

type Animal interface {
    Eat()
}
type Describle interface {
    Describled()
}
type AdvanceAnimal interface {
    Animal
    Describle
}
type Dog struct {
}
func (d Dog) Eat() {
    fmt.Println("狗吃屎")
}
func (d Dog) Describled() {
    fmt.Println("狗")
}
func test() {
    var d Dog
    var a AdvanceAnimal
    a = d
    a.Eat()
    a.Describled()
}

  

Second, reflection

  definition

  Empty interface can store any type of variable, to obtain a dynamically variable at run-time type information and value information is reflected

//获取类型信息:reflect.TypeOf
import {
    "fmt"
    "reflect"
}
func reflect_example(a interface{}) {
    t := reflect.TypeOf(a)
    fmt.Printf("type of a is:%v\n",t)
}
func test(){
    var x float32 = 3.4
    reflect_example(x)
}

//获取变量的类型:Type.Kind()
import (
    "fmt"
    "reflect"
}
func reflect_example(a interface{}) {
    t := reflect.TypeOf(a)
    fmt.Printf("type of a is :%v\n",t)
    k := t.Kind()
    switch k {
    case reflect.Int64:
        fmt.Println("a is int64")
    case reflect.String:
        fmt.Printf("a is string")
    }
}
func test() {
    var x float32 = 3.4
    reflect_example(x)
}

//获取值信息:reflect.ValueOf
func reflect_value(a interface{}) {
    v := reflect.ValueOf(a)
    k := v.Kind()
    switch k {
    case reflect.Int64:
        fmt.Printf("a is int64,value is :%d",v.int())
    case reflect.Float64:
        fmt.Printf("a is Float64,value is:%f",v.Float())
    }
}
func test() {
    var x float64 = 3.4
    reflect_value(x)
}

//反射设置变量值:value.Elem().SetFloat()
func reflect_set_value(a interface{}) {
    v := reflect.ValueOf(a)
    k := v.Kind()
    switch k {
    reflect.Int64 Case: 
        v.SetInt (100) 
        fmt.Printf ( "A Int64 IS, IS value:% D", v.Int ()) 
    Case reflect.Float64: 
        v.SetFloat (6.8) 
        fmt.Printf ( "A Float64 IS, IS value:% f ", v.Float ()) 
    Case reflect.Ptr: 
        fmt.Printf (" the SET 6.8 \ to the n-A ") 
        . qv.Elem () SetFloat (6.8) // Elem () fairly assignment of the pointer * 
    } 
} 
FUNC Test () { 
    var X = 3.4 float64 
    reflect_set_valur (& X) 
    fmt.Printf ( "X% value V iS \ n-", X) 
} 
/ * 
Note:
    var *p int = new(int)
    * p = 100 // normal pointer assignment, and set to a value variable type requires matching 
* /

  Reflector structure

  Information acquisition and the installation structure of the field

// Get information structure 
type struct {Student 
    the Name String 
    Sex int 
    Age int 
} 
FUNC Test () { 
    var S Student 
    V: = reflect.ValueOf (S) 
    T: = v.Type () 
    kind: = t.Kind () 
    {kind Switch 
    Case reflect.Int64: 
        fmt.Printf ( "S IS Int64 \ n-") 
    Case reflect.Float32: 
        fmt.Println ( "S IS Float32 \ n-") 
    Case reflect.Struct: 
        fmt.Printf ( "IS struct S \ n-") 
        fmt.Printf (" NUM Field of iS S% D \ n-", v.NumField ()) // Get the number of parameters of the structure with NumField () 
        for I: = 0; I <v.NumField (); I ++ { 
            Field: = v.Field (I) 
            fmt.Printf (" name:% S type: V value%:% V \ n-", t.Field (I) .Name, Field.Type (), field.Interface ()) 
        }
    default: 
        fmt.Println ( "default") 
    } 
} 

// set the value of the field associated structure 
type struct {Student 
    the Name stirng 
    Sex int 
    Age int 
} 
FUNC Test () { 
    var S Student 
    V: = reflect.ValueOf (& S) 
    V .Elem (). Field, (0) .SetString ( "stu01") 
    v.Elem (). FieldByName ( "Sex"). SetInt (2) 
    v.Elem (). FieldByName ( "Age"). SetInt (15) 
    fmt.Printf ( "S:% # V \ n-", S) 
}

  Access to information and call structure methods

//获取结构体的方法信息
type Student struct {
    Name string
    Sex int
    Age int
    Score float32
}
func (s *Student) SetName(name string) {
    s.Name = name
}
func (s *Student) Print(){
    fmt.printf("%#v\n",s)
{
func test(){
    var s Student
    s.SetName("xxx")
    v := reflect.ValueOf(&s)
    t := v.Type()
    fmt.Printf("struct student have %d methods\n",t.NumMethod())
    for i := 0;i<NumMethod();i++ {
        method := t.Method(i)
        fmt.Printf("struct %d method,name:%s type :%v\n",i,method.Name,method.Type) 
method // Call structural body
    }
}
 
type struct {Student 
    the Name String 
    Sex int 
    Age int 
    Score a float 32 
} 
FUNC (S * Student) SetName (String name) { 
    s.Name name = 
} 
FUNC (S * Student) the Print () { 
    fmt.Printf ( "# V% \ n-", S) 
} 
FUNC test2 () { 
    var S Student 
    s.SetName ( "XXX") 
    V: = reflect.ValueOf (& S) 
    M1: = v.MethodByName ( "the Print" ) 
    var args [] reflect.Value 
    m1.Call (args) 
// call that has parameters of the structure 
    M2: = v.MethodByName ( "SetName") 
    var args2 [] reflect.Value 
    name: = "stu01" 
    nameVal: = reflect.ValueOf (name)
    args2 = append(args2,nameVal)
    m2.Call(args2)
    m1.Call(args)
}

  

  

Guess you like

Origin www.cnblogs.com/parallel-Y/p/11420757.html