当前位置: 移动技术网 > IT编程>脚本编程>Go语言 > Go-接口(作用类似python类中的多态)

Go-接口(作用类似python类中的多态)

2019年11月22日  | 移动技术网IT编程  | 我要评论

一.定义接口

type person interface {
    run()   //只要有run方法的都算 person结构体
}
//还有定义方法
type person2 interface {
    speak()
    person  //相当于run()
}

二.实际使用

package main

import "fmt"

type person interface {
    run()
}

type person2 struct {
    name string
}
func (p person2)run(){
    fmt.println("我会走")
}

type person3 struct {
    name string
}
func (p person3)run(){
    fmt.println("我会飞")
}

func test(p person){
    p.run()
}

func main() {
    p1 :=person2{}
    p2 :=person3{}
    test(p1)
    test(p2)
}

//p1与p2都有run方法都算person结构体,所有都可以由run方法

三.匿名空接口

interface {}

//可以接受所有数据类型
package main

import "fmt"
func test(a interface{}){fmt.println(a)}
func main(){
    test(1)
    test("www")
}

四.类型断言

写法一:

package main
import "fmt"

type person struct {
    name  string
}
func test(a interface{}){
    _,err :=a.(*person)
    if !err{
        fmt.println("是person")
    }
}

func main(){
    a := person{name: "p1"}
    test(a)
}

写法二:

package main

import (
    "fmt"
)

type person struct {
    name string
}

func test(a interface{}) {
    switch a.(type) {   //如果要获取a的对象就astruct :=a.(type)
    case person:
        fmt.println("是person")
    default:
        fmt.println("不是person")
    }
}
func main() {
    a := person{name: "p1"}
    test(a)
}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网