golang Interface

CSDN find a web page, according to a copy practice.

Almost all in the usage scenarios.

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)

		}
	}
}

  Output:

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.

  

Guess you like

Origin www.cnblogs.com/aguncn/p/11713897.html