前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >golang学习笔记——面向对象(接口)

golang学习笔记——面向对象(接口)

作者头像
码缘
发布2021-03-04 15:06:16
3140
发布2021-03-04 15:06:16
举报
文章被收录于专栏:PHP修行之路PHP修行之路

接口

  • 定义及使用

package main

import (

"fmt"

)

//定义一个接口

type Human interface {

sayHello()

}

type Student struct {

name string

age int

}

type Teacher struct {

group string

}

func (stu *Student) sayHello() {

fmt.Printf("Student[%s,%d] \n", stu.name, stu.age)

}

func (tea *Teacher) sayHello() {

fmt.Printf("Teacher[%s] \n", tea.group)

}

func WhoSay(tmp Human) {

tmp.sayHello()

}

func main() {

//第一种使用

s := &Student{"Bon", 12}

t := &Teacher{"math"}

WhoSay(s)

WhoSay(t)

//第二种使用 创建切片

slic := make([]Human, 2)

slic[0] = s

slic[1] = t

for _, v := range slic {

v.sayHello()

}

}

  • 接口继承

package main

import (

"fmt"

)

//定义一个接口

type Humaner interface {

sayHello()

}

//继承Humaner

type Personer interface {

Humaner

sayWorld(str string)

}

type Student struct {

name string

age int

}

func (stu *Student) sayHello() {

fmt.Printf("Student[%s,%d] \n", stu.name, stu.age)

}

func (stu *Student) sayWorld(str string) {

fmt.Println(str)

}

func main() {

var i Personer

s := &Student{"Bob", 23}

i = s

i.sayHello()

i.sayWorld("song")

}

  • 接口转化(超集可以转化为子集,子集不可以转化为超集)

package main

import (

"fmt"

)

//定义一个接口

type Humaner interface { //子集

sayHello()

}

type Personer interface { //超集

Humaner

sayWorld(str string)

}

type Student struct {

name string

age int

}

func (stu *Student) sayHello() {

fmt.Printf("Student[%s,%d] \n", stu.name, stu.age)

}

func (stu *Student) sayWorld(str string) {

fmt.Println(str)

}

func main() {

var i Personer

i = &Student{"Tom", 16}

var h Humaner

//子集不能转为超集

// i = h

//超集可以转化为子集

h = i

h.sayHello()

}

  • 空接口(可以保存任意类型的数据)

package main

import (

"fmt"

)

func xxx(arg ...interface{}) {

}

func main() {

//空接口可保存任意类型的数据

var i interface{}

i = 10

fmt.Println(i)

var m interface{}

m = "hello world"

fmt.Println(m)

}

  • 判断空接口存储的数据类型

package main

import (

"fmt"

)

func main() {

var i interface{}

i = 10

//使用 变量.(类型) 判断数据数据类型

if value, ok := i.(int); ok == true {

fmt.Println(value)

}

}

package main

import (

"fmt"

)

func main() {

var i interface{}

i = 10

//使用 变量.(type) 判断数据数据类型

switch value := i.(type) {

case int:

fmt.Printf("int 类型 %d \n", value)

case string:

fmt.Print("string 类型 %s \n", value)

}

}

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021-02-28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档