1.接口会自动和拥有相同方法的结构体关联
/*
只要一个变量,含有接口类型中的所有方法,那么这个变量就实现这个接口。
如果一个变量含有了多个interface类型的方法,那么这个变量就实现了多个接口。
*/
type MyInterface interface{
GetName() string
GetAge() int
}
type StringInterface interface{
SumAgeSa() int
}
type CommonInterface interface{
MyInterface
StringInterface
GetGender() string
}
type Employee struct {
name string
age int
salary int
gender string
}
func (self *Employee) GetName() string {
return self.name
}
func (self *Employee) GetAge() int {
return self.age
}
func (self *Employee) SumAgeSa() int {
return self.age + self.salary
}
func (self *Employee) GetGender() string {
return self.gender
}
/*自动关联上了*/
func IntRun() {
// 空接口的使用,空接口类型的变量可以保存任何类型的值
// 空格口类型的变量非常类似于弱类型语言中的变量
var varEmptyInterface interface{}
fmt.Println("varEmptyInterface is of type %T\n", varEmptyInterface)
varEmptyInterface = 100
y := varEmptyInterface.(int) //这里可以类型转换(类型断言 )
fmt.Println("varEmptyInterface is of type int", varEmptyInterface, y)
varEmptyInterface = "Golang"
k, err := varEmptyInterface.(string) //待判断的类型转换(类型断言 )
if err {
fmt.Println("varEmptyInterface is of type string", varEmptyInterface, k)
}
varEmployee := Employee{
name: "Jack Ma",
age: 50,
salary: 100000000,
gender: "Male",
}
var mm MyInterface = &varEmployee
fmt.Println(mm.GetName())
fmt.Println(mm.GetAge())
//这里可以调用组合内的所有接口
var ww CommonInterface = &varEmployee
fmt.Println(ww.GetAge(), ww.GetGender(), ww.GetName(), ww.SumAgeSa())
}
2.通过类型获取值
func IntRun() {
var varEmptyInterface interface{}
varEmptyInterface = 100
y := varEmptyInterface.(int) //这里可以类型转换(类型断言 )
fmt.Println("varEmptyInterface is of type int", varEmptyInterface, y)
classifier(varEmptyInterface)
}
/*
通过类型获取值
*/
func classifier(items ...interface{}) {
for i, x := range items {
switch x.(type) {
case bool:
fmt.Println("classifier", "bool", i, x)
case float64:
fmt.Println("classifier","float64", i, x)
case int, int64:
fmt.Println("classifier","int", i, x)
case nil:
fmt.Println("classifier","nil", i, x)
case string:
fmt.Println("classifier","string", i, x)
default:
fmt.Println("classifier","other", i, x)
}
}
}
3.简单工厂
/*
简单工厂例子
*/
type Animal interface {
Sleep()
Age() int
Type() string
}
type Cat struct {
MaxAge int
}
func (this *Cat) Sleep() {
fmt.Println("Cat need sleep")
}
func (this *Cat) Age() int {
return this.MaxAge
}
func (this *Cat) Type() string {
return "Cat"
}
type Dog struct {
MaxAge int
}
func (this *Dog) Sleep() {
fmt.Println("Dog need sleep")
}
func (this *Dog) Age() int {
return this.MaxAge
}
func (this *Dog) Type() string {
return "Dog"
}
func Factory(name string) Animal {
switch name {
case "dog":
return &Dog{MaxAge: 20}
case "cat":
return &Cat{MaxAge: 10}
default:
panic("No such animal")
}
}
还没有评论,来说两句吧...