码迷,mamicode.com
首页 > 其他好文 > 详细

golang中的接口

时间:2019-10-21 16:36:25      阅读:93      评论:0      收藏:0      [点我收藏+]

标签:dex   unknown   UNC   package   场景   each   else   pack   成功   

CSDN找的一个网页,照着抄练一次。

差不多的使用场景都在了。

package main

import (
	"fmt"
)

type People interface {
	ReturnName() string
}

type Role interface {
	People
	ReturnRole() string
}

type Student struct {
	Name string
}

type Teacher struct {
	Name string
}

func (s Student) ReturnName() string {
	return s.Name
}

func (t *Teacher) ReturnName() string {
	return t.Name
}

func (s Student) ReturnRole() string {
	return "student"
}

func CheckPeople(test interface{}) {
	if _, ok := test.(People); ok {
		fmt.Println("Student implements People")
	}
}

func main() {
	cbs := Student{Name: "This is a student."}
	sss := Teacher{Name: "This is a teacher."}
	CheckPeople(cbs)

	var a People
	var b Role
	a = cbs
	name := a.ReturnName()
	fmt.Println(name)
	
	a = &sss
	name = a.ReturnName()
	fmt.Println(name)

	b = cbs
	role := b.ReturnRole()
	fmt.Println(role)

	Params := make([]interface{}, 3)
	Params[0] = 88
	Params[1] = "This is a string"
	Params[2] = Student{Name: "cbs"}

	for index, v := range Params {
		if _, ok := v.(int); ok {
			fmt.Printf("Params[%d] is int type\n", index)
		} else if _, ok := v.(string); ok {
			fmt.Printf("Params[%d] is string type\n", index)
		} else if _, ok := v.(Student); ok {
			fmt.Printf("Params[%d] is custom Student type\n", index)
		} else {
			fmt.Printf("list[%d] unknown type.\n", index)
		}
	}

	for index, v := range Params {
		switch value := v.(type) {
		case int:
			fmt.Printf("Params[%d] is int type: %d\n", index, value)
		case string:
			fmt.Printf("Params[%d] is string type: %s\n", index, value)
		case Student:
			fmt.Printf("Params[%d] is custom Student type: %s\n", index, value)
		default:
			fmt.Printf("list[%d] unknown type.\n", index)

		}
	}
}

  输出:

D:/go-project/src/InterfaceGo/InterfaceGo.exe  [D:/go-project/src/InterfaceGo]
Student implements People
This is a student.
This is a teacher.
student
Params[0] is int type
Params[1] is string type
Params[2] is custom Student type
Params[0] is int type: 88
Params[1] is string type: This is a string
Params[2] is custom Student type: {cbs}
成功: 进程退出代码 0.

  

golang中的接口

标签:dex   unknown   UNC   package   场景   each   else   pack   成功   

原文地址:https://www.cnblogs.com/aguncn/p/11713897.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!