zoukankan      html  css  js  c++  java
  • Go-接口(作用类似python类中的多态)

    一.定义接口

    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)
    }
    
  • 相关阅读:
    GitLab 介绍
    git 标签
    git 分支
    git 仓库 撤销提交 git reset and 查看本地历史操作 git reflog
    git 仓库 回退功能 git checkout
    python 并发编程 多进程 练习题
    git 命令 查看历史提交 git log
    git 命令 git diff 查看 Git 区域文件的具体改动
    POJ 2608
    POJ 2610
  • 原文地址:https://www.cnblogs.com/pythonywy/p/11908003.html
Copyright © 2011-2022 走看看