前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Golang之interface(多态,类型断言)

Golang之interface(多态,类型断言)

作者头像
超蛋lhy
发布2018-08-31 15:41:03
1.7K0
发布2018-08-31 15:41:03
举报
文章被收录于专栏:PythonistaPythonista

多态用法

代码语言:javascript
复制
package main

//一种事物的多种形态,都可以按照统一的接口进行操作
//多态
import (
    "fmt"
    "math/rand"
    "sort"
)

type Student struct {
    Name     string
    Id       string
    Age      int
    sortType int
}
type Book struct {
    Name   string
    Author string
}

//切片默认传地址
type StudentArray []Student

func (p StudentArray) Len() int {
    return len(p)
}

func (p StudentArray) Less(i, j int) bool {
    return p[i].Name < p[j].Name
}

func (p StudentArray) Swap(i, j int) {
    p[i], p[j] = p[j], p[i]
}

func main() {
    var stus StudentArray
    for i := 0; i < 10; i++ {
        stu := Student{
            Name: fmt.Sprintf("stu%d", rand.Intn(100)),
            Id:   fmt.Sprintf("110%d", rand.Int()),
            Age:  rand.Intn(100),
        }
        stus = append(stus, stu)
    }
    for _, v := range stus {
        fmt.Println(v)
    }

    fmt.Println("\n\n")
    sort.Sort(stus)
    for _, v := range stus {
        fmt.Println(v)
    }
}

 接口嵌套

代码语言:javascript
复制
package main

import "fmt"
//接口嵌套 一个接口可以嵌套在另外的接口
type Reader interface {
    Read()
}
type Writer interface {
    Write()
}
type ReadWriter interface {
    Reader
    Writer
}
type File struct {
}

func (f *File) Read() {
    fmt.Println("read data")
}

func (f *File) Write() {
    fmt.Print("write data")
}
func Test(rw ReadWriter) {
    rw.Read()
    rw.Write()
}

func main() {
    var f File
    Test(&f)
}

 类型断言

代码语言:javascript
复制
package main

import "fmt"

type Student struct {
    Name string
    Sex  string
}
//类型断言
//一个判断传入参数类型的函数
func just(items ...interface{}) {
    for index, v := range items {
        switch v.(type) {
        case bool:
            fmt.Printf("%d params is bool,value is %v\n", index, v)
        case int, int64, int32:
            fmt.Printf("%d params is int,value is %v\n", index, v)
        case float32, float64:
            fmt.Printf("%d params is float,value is %v\n", index, v)
        case string:
            fmt.Printf("%d params is string,value is %v\n", index, v)
        case Student:
            fmt.Printf("%d params student,value is %v\n", index, v)
        case *Student:
            fmt.Printf("%d params *student,value is %v\n", index, v)

        }
    }
}
func main() {
    var b Student = Student{
        Name: "stu01",
        Sex:  "female",
    }
    just(28, 8.2, "this is a test", b, &b)

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

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

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

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

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