package main
import "fmt"
func main() {
var x interface {}
x = "hello golang"
v,ok :=x.(string)
if ok {
fmt.PrintIn(v)
}else {
fmt.PrintIn("非字符串类型")
}
}
四、值接收者和指针接收者
1、值接收者
如果结构体中的方法是值接收者,那么实例化后的结构体值类型和结构体指针类型都可以赋值给接口变量
Go复制代码
package main
import "fmt"
type Usb interface {
Start()
Stop()
}
type Phone struct {
Name string
}
func (p Phone) Start() {
fmt.PrintIn(p.Name,"开始工作")
}
func (p Phone) Stop() {
fmt.Println("phone 停止")
}
func main() {
phone1 := Phone{
Name:"华为手机"
}
var p1 Usb = phone1 //phone1 实现了 Usb接口 phone1 是 Phone 类型
p1.Start()
phone2 := &Phone{ //华为手机开始工作
Name:"苹果手机"
}
var p2 Usb = phone2 //phone2 实现了 Usb 接口 phone2 是 *Phone 类型
p2.Start()
}
package main
import "fmt"
type Usb interface {
Start()
Stop()
}
type Phone struct {
Name string
}
func (p *Phone) Start() {
fmt.Println(p.Name, "开始工作")
}
func (p *Phone) Stop() {
fmt.Println("phone 停止")
}
func main() {
/*错误写法
phone1 := Phone{
Name: "小米手机",
}
var p1 Usb = phone1
p1.Start()
*/
//正确写法
phone2 := &Phone{
Name: "苹果手机",
}
var p2 Usb = phone2 //phone2 实现了 Usb 接口 phone2 是 *Phone 类型
p2.Start()
//苹果手机 开始工作
}
五、一个结构体实现多个接口
Golang 中一个结构体也可以实现多个接口
Go复制代码
package main
import "fmt"
type AInterface interface {
GetInfo() string
}
type Binterface interface {
SetInfo(string,int)
}
type People struct{
Name string
Age int
}
func (p People) GetInfo() string(){
return fmt.Sprintf("姓名:%v 年龄:%d",p.Name,p.Age)
}
func (p *People) SetInfo(name string, age int) {
p.Name = name
p.Age = age
}
func main() {
ver people =&People{
Name:"Snail",
Age: 20,
}
// people实现了 Ainterface 和 Binterface
var p1 AInterface = people
var p2 Binterface = people
fmt.PrintIn(p1.GetInfo()) //姓名:Snail 年龄:20
p2.SetInfo("pupu",21)
fmt.PrintIn(p1.GEtInfo) //姓名:pupu 年龄:21
}
六、接口嵌套
接口与接口间可以通过嵌套创造出新的接口
Go复制代码
package main
import "fmt"
type SayInterface interface {
say()
}
type MoveInterface interface {
move()
}
//接口嵌套
type Animal interface {
SayInterface
MoveInterface
}
type Cat struct {
name string
}
func (c Cat) say() {
fmt.PrintIn("喵喵喵")
}
func (c Cat) move(){
fmt.PrintIn("猫会动")
}
func main() {
var x Animal
x = Cat{name: "花花"}
x.move() // 猫会动
x.say() // 喵喵喵
}