golang之interface(接口)与 reflect 机制

一、概述

  什么是interface,简单的说,interface是一组method的组合,通过interface来定义对象的一组行为;

  interface类型定义了一组方法,如果某个对象实现了某个接口的所有方法,则此对象就实现了此接口;

  1 package main
  2 
  3 import "fmt"
  4 
  5 type Human struct {
  6     name  string
  7     age   int 
  8     phone string
  9 }
 10 
 11 type Student struct {
 12     Human  //匿名函数
 13     school string
 14     loan   float32
 15 }
 16 
 17 type Employee struct {
 18     Human
 19     company string
 20     money   float32
 21 }
 22 
 23 //Human对象实现Sayhi方法
 24 func (h *Human) Sayhi() {
 25     fmt.Printf("hi, I am %s you can call me on %s\n", h.name, h.phone)
 26 }
 27 
 28 //Human对象实现了Sing方法
 29 func (h *Human) Sing(lyrics string) {
 30     fmt.Println("lalala...", lyrics)
 31 }
 32 
 33 //Human对象实现了Guzzle方法
 34 func (h *Human) Guzzle(beerStein string) {
 35     fmt.Println("Guzzle Guzzle...", beerStein)
 36 }
 37 
 38 //Student 实现了BorrowMoney方法
 39 func (s *Student) BorrowMoney(amount float32) {
 40     s.loan += amount
 41 }
 42 
 43 //Empolyee 重载了Human的Sayhi的方法
 44 func (e *Employee) Sayhi() {
 45     fmt.Printf("hi, I am %s, I work at %s. call me on %s\n", e.name, e.company, e.phone)
 46 }
 47 
 48 //Employee实现了SpendSalary的方法
 49 func (e *Employee) SpendSalary(amount float32) {
 50     e.money -= amount
 51 }
 52 
 53 //define interface
 54 /*
 55 type Men interface {
 56     Sayhi()
 57     Sing(lyrics string)
 58     Guzzle(beerStein string)
 59 }
 60 
 61 type YoungChap interface {
 62     Sayhi()
 63     Sing(song string)
 64     BorrowMoney(amount float32)
 65 }
 66 
 67 type ElderlyGent interface {
 68     Sayhi()
 69     Sing(song string)
 70     SpendSalary(amount float32)
 71 }
 72 */
 73 
 74 //interface Men被Human,Student, Employee都实现
 75 // Student, Employee包含了Human匿名字段,所有也包含了其接口实现
 76 type Men interface {
 77     Sayhi()
 78     Sing(lyrics string)
 79 }
 80 
 81 func main() {
 82     mike := Student{Human{"Mike", 24, "22-22-xx"}, "MIT", 0.00}
 83     paul := Student{Human{"paul", 26, "23-32-xx"}, "Harvard", 5.00}
 84     sam := Employee{Human{"Sam", 46, "33-33-33"}, "Gling inc", 1000}
 85     Tom := Employee{Human{"Tom", 33, "33-334-11"}, "Things ltd", 400}
 86 
 87     var i Men //interface type
 88     i = &mike
 89     fmt.Println("this is Mike, a Student\n")
 90     i.Sayhi()
 91     i.Sing("my name is Mike")
 92 
 93     i = &Tom
 94     fmt.Println("this is Tom, an employee\n")
 95     i.Sayhi()
 96     i.Sing("my name is Tom")
 97 
 98     x := make([]Men, 3)
 99     x[0], x[1], x[2] = &paul, &sam, &mike
100     for _, value := range x {
101         value.Sayhi()
102     }
103 }

二、反射机制

 1 package main
 2 
 3 import (
 4     "fmt"
 5     "reflect"
 6 )
 7 
 8 func main() {
 9     var x float64 = 3.4
10     p := reflect.ValueOf(&x)
11     v := p.Elem()
12     fmt.Println(v)
13     v.SetFloat(8.3)
14     fmt.Println(v)
15 }

 

posted on 2016-09-11 20:56  阳台  阅读(2547)  评论(0编辑  收藏  举报

导航