GO系列(1)-interface{} 多参数... 封装继承多态
一. Interface{}
interface可以理解为iOS中的NSObject,是一种单独的类型
1. 其他类型与interface{}的互相转换
var v interface{} = 1
var s uint8 = 1
temp1 := int(s)
temp2 := v.(int)
fmt.Println(temp1,temp2)
2. interface{}转换为其他类型 的断言
interface转换成具体类型调用方式:interfaceVar.(具体类型)
原理:断言
断言成功返回true,失败false
func testInterface2String() {
a := "tomxiang"
v, ok := interface{}(a).(string) // 将 a 转换为接口类型
if ok {
fmt.Printf("v type is %T\\n", v)
}
fmt.Println(a)
}
二. 三个...
参考:https://geekr.dev/posts/go-func-params-and-return-values
XXX(args ... interface{})这种方式接收参数,如果你调用xxx(ids...), 会把ids直接传递过去,没有包装的开销。XXX(ids)这种会有包装开销,会申请个新切片,把ids作为切片第一个元素
1.1 切片正常传递
func testInterface1() {
var ids1 = []interface{}{1, 2.2, 3.4}
printInterface1(ids1)
}
func printInterface1(vals []interface{}) {
for _, val := range vals {
fmt.Println(val)
}
}
输出结果
1
2.2
3.4
1.2 接收的是新的切片0号元素
func testInterface2() {
var ids2 = []interface{}{1, 2.2, 3.4}
printInterface2(ids2)
}
func printInterface2(vals ...interface{}) {
for _, val := range vals {
fmt.Println(val)
}
}
输出结果:
[1 2.2 3.4]
1.3 接收的是新的切片
func testInterface3() {
var ids3 = []interface{}{1, 2.2, 3.4}
printInterface3(ids3...)
}
func printInterface3(vals ...interface{}) {
for _, val := range vals {
fmt.Println(val)
}
}
输出结果
1
2.2
3.4
三. 封装 继承 多态
package main
import "fmt"
func main() {
/*封装*/
peo := new(People)
peo.SetName("derek")
peo.SetAge(22)
fmt.Println(peo.GetName(),peo.GetAge()) //derek 22
/*继承*/
tea := Teacher{People{"derek-teacher",22},"911"}
fmt.Println(tea.classroom,tea.name,tea.age) //911 derek 22
stu := Student{People{"derek-student",11},"919"}
fmt.Println(stu.classroom,stu.name,stu.age) //911 derek 22
//tea.run()
//stu.run()
/*多态*/
allrun(&tea)
allrun(&stu)
}
type Live interface {
run()
}
func allrun(live Live) {
live.run()
}
type People struct {
name string
age int
}
func (p *People) SetName(name string) {
p.name = name
}
func (p *People) SetAge(age int) {
p.age = age
}
func (p *People) run() {
fmt.Println("%v在跑步",p.name)
}
func (p *People) GetName() string{
return p.name
}
func (p *People) GetAge() int{
return p.age
}
type Teacher struct{
People
classroom string
}
func (tea *Teacher) run() {
fmt.Println(tea.name,"在跑步")
}
type Student struct{
People
classroom string
}
func (stu *Student) run() {
fmt.Println(stu.name,"在跑步")
}
下载链接
https://github.com/xcysuccess/go-demo/tree/master/hello