标签:phone efault title oop 定义 hone tle lin 接口
@
type USB interface{
Name() string
Connect()
}
type PhoneConnecter struct{
name string
}
func (pc PhoneConnecter) Name() string {
return pc.name
}
func (pc PhoneConnecter) Connect() {
fmt.Println("connect:",pc.name)
}
func main(){
a := PhoneConnecter{"PhoneConnecter"}
a.Connect()
Disconnect(a)
}
func Disconnect(usb USB){
fmt.Println("Disconnect.")
}
/*
> Output:
connect: PhoneConnecter
Disconnect.
*/
type USB interface{
Name() string
Connecter
}
type Connecter interface {
Connect()
}
...
...
func Disconnect(usb USB){
//简单的类型断言
if pc,ok := usb.(PhoneConnecter);ok {
fmt.Println("Disconnect:",pc.name)
return
}
fmt.Println("Unknown device.")
}
/*
> Output:
command-line-arguments
connect: PhoneConnecter
Disconnect: PhoneConnecter
*/
func Disconnect(usb interface{}){}
func Disconnect(usb interface{}){
//type switch,让系统自己判断类型,然后赋值给type
//一般是参数是空接口的时候用
switch v := usb.(type){
case PhoneConnecter:
fmt.Println("Disconnect:",v.name)
default:
fmt.Println("Unknown device.")
}
}
type USB interface{
Name() string
Connecter
}
type Connecter interface {
Connect()
}
type PhoneConnecter struct{
name string
}
func (pc PhoneConnecter) Name() string {
return pc.name
}
func (pc PhoneConnecter) Connect() {
fmt.Println("connect:",pc.name)
}
func main(){
pc := PhoneConnecter{"PhoneConnecter"}
var a Connecter
a = Connecter(pc)
a.Connect()
}
/*
> Output:
command-line-arguments
connect: PhoneConnecter
*/
func main(){
var a interface{}
fmt.Println(a==nil)
var p *int =nil
a=p
fmt.Println(a==nil)
}
/*
true
false
*/
//第一个是nil
//第二个是存的指向为空的指针,就不是nil了
标签:phone efault title oop 定义 hone tle lin 接口
原文地址:https://www.cnblogs.com/leafs99/p/golang_basic_09.html