您的位置:首页 > 编程语言 > Go语言

golang之interface(接口)与 reflect 机制

2016-09-11 20:56 357 查看
一、概述

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

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

package main

import "fmt"

type Human struct {
name  string
age   int
phone string
}

type Student struct {
Human  //匿名函数
school string
loan   float32
}

type Employee struct {
Human
company string
money   float32
}

//Human对象实现Sayhi方法
func (h *Human) Sayhi() {
fmt.Printf("hi, I am %s you can call me on %s\n", h.name, h.phone)
}

//Human对象实现了Sing方法
func (h *Human) Sing(lyrics string) {
fmt.Println("lalala...", lyrics)
}

//Human对象实现了Guzzle方法
func (h *Human) Guzzle(beerStein string) {
fmt.Println("Guzzle Guzzle...", beerStein)
}

//Student 实现了BorrowMoney方法
func (s *Student) BorrowMoney(amount float32) {
s.loan += amount
}

//Empolyee 重载了Human的Sayhi的方法
func (e *Employee) Sayhi() {
fmt.Printf("hi, I am %s, I work at %s. call me on %s\n", e.name, e.company, e.phone)
}

//Employee实现了SpendSalary的方法
func (e *Employee) SpendSalary(amount float32) {
e.money -= amount
}

//define interface
/*
type Men interface {
Sayhi()
Sing(lyrics string)
Guzzle(beerStein string)
}

type YoungChap interface {
Sayhi()
Sing(song string)
BorrowMoney(amount float32)
}

type ElderlyGent interface {
Sayhi()
Sing(song string)
SpendSalary(amount float32)
}
*/

//interface Men被Human,Student, Employee都实现
// Student, Employee包含了Human匿名字段,所有也包含了其接口实现
type Men interface {
Sayhi()
Sing(lyrics string)
}

func main() {
mike := Student{Human{"Mike", 24, "22-22-xx"}, "MIT", 0.00}
paul := Student{Human{"paul", 26, "23-32-xx"}, "Harvard", 5.00}
sam := Employee{Human{"Sam", 46, "33-33-33"}, "Gling inc", 1000}
Tom := Employee{Human{"Tom", 33, "33-334-11"}, "Things ltd", 400}

var i Men //interface type
i = &mike
fmt.Println("this is Mike, a Student\n")
i.Sayhi()
i.Sing("my name is Mike")

i = &Tom
fmt.Println("this is Tom, an employee\n")
i.Sayhi()
i.Sing("my name is Tom")

x := make([]Men, 3)
x[0], x[1], x[2] = &paul, &sam, &mike
for _, value := range x {
value.Sayhi()
}
}


二、反射机制

package main

import (
"fmt"
"reflect"
)

func main() {
var x float64 = 3.4
p := reflect.ValueOf(&x)
v := p.Elem()
fmt.Println(v)
v.SetFloat(8.3)
fmt.Println(v)
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: