在Go语言中接口是一种类型,一种抽象的类型。相较于之前章节中讲到的那些具体类型更注重“我是谁”,接口类型更注重“我能做什么”的问题。接口类型就像是一种约定——概括了一种类型应该具备哪些方法,在Go语言中提倡使用面向接口的编程方式实现解耦
了解为什么需要接口以及接口的特点掌握接口的声明和使用掌握接口值的概念掌握空接口的特点及其使用场景
指针传值上面代码块的例子是值传值
package main
import 'fmt'
func main() {
var m Move
p := Person{
Name: 'lwl',
Age: 18,
}
p1 := &Person{
Name: 'zq',
Age: 18,
}
m = p //值类型 无法赋值,所以报错
m = p1 //指针
p.move() //lwl在移动...
p1.move() //zq在移动...
fmt.Println(m)
}
type Person struct {
Name string
Age int8
}
type Move interface {
move()
}
//使用指针接受实现接口,只有类型是指针能够保存到接口变量中
func (p *Person) move() {
fmt.Printf('%s在移动...
', p.Name)
}
//空接口
类型断定
var emptyinterface interface{}
emptyinterface = true
_, ok := emptyinterface.(int)
fmt.Println(ok)//false
// justifyType 对传入的空接口类型变量x进行类型断言
func justifyType(x interface{}) {
switch v := x.(type) {
case string:
fmt.Printf('x is a string,value is %v
', v)
case int:
fmt.Printf('x is a int is %v
', v)
case bool:
fmt.Printf('x is a bool is %v
', v)
default:
fmt.Println('unsupport type!')
}
}
空接口作为map的值
var studentInfo = make(map[string]interface{})
studentInfo['name'] = '沙河娜扎'
studentInfo['age'] = 18
studentInfo['married'] = false
fmt.Println(studentInfo)
文章为作者独立观点,不代表股票交易接口观点