首页 技术 正文
技术 2022年11月18日
0 收藏 806 点赞 4,900 浏览 1559 个字

多态用法

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 []Studentfunc (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 := ; i < ; i++ {
stu := Student{
Name: fmt.Sprintf("stu%d", rand.Intn()),
Id: fmt.Sprintf("110%d", rand.Int()),
Age: rand.Intn(),
}
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)
}
}

接口嵌套

package mainimport "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)
}

类型断言

package mainimport "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(, 8.2, "this is a test", b, &b)}
上一篇: Vue 路由缓存
下一篇: __imp___vsnprintf
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,216
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,673
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,507
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,278
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,924
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,082