欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-08-30 14:10:02
一.定义接口 二.实际使用 三.匿名空接口 四.类型断言 写法一 : 写法二: ......

一.定义接口

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)
}