接口的定义
- 接口由使用者定义
- 接口实现是隐士的
- 只要实现接口里的方法
- 接口不是简单的引用,他包含实现者类型和实现者的指针
- 接口变量自带指针
- 接口变量采用值传递,几乎不需要使用接口的指针
- 指针接收这实现只能以指针方式使用,值接受者都可以
- 接口对象不能调用接口实现对象的属性
- interface可以被任意的对象实现
- 一个对象可以实现任意多个interface
- 任意的类型都实现了空interface(我们这样定义:interface{}),也就是包含0个method的interface
查看接口变量
-
interface{}任何类型
-
Type Assertion
if 变量x, ok := r.(*某包.某类型); ok { fmt.Println(变量x.已知字段) } else { fmt.Println("x is not 某类型") }
-
Type Switch
switch v := 某变量.(type) {
case 某包.某类型:
fmt.Println("Contents:", v.字段)
case 某包.某类型:
fmt.Println("name:", v.字段)
}
接口的组合
type A interface {
get(url string) string
}
type B interface {
post(url string)string
}
//组合接口类型
type AandB interface {
A
B
}
type C struct {
id int
name string
}
func (s C)get(url string)string {
return "get func"
}
func (s C)post(url string)string {
return "post func"
}
func test(x AandB) {
//组合接口类型的x既可以调用A接口的方法,也可以调用B接口的方法
x.get("")
x.post("")
}
func test1() {
var t AandB
t=C{1,"Mike"}
t.get("")
t.post("")
}
网友评论