//type 关键字 接口是特殊的数据类型
//接口是一组方法的集合
//用于实现不同类型(结构体)的相同方法
//版本2 区别在于多了要调用da()函数
type cat struct{}
func (c cat) say() {
fmt.Println("miaomiao")
}
type dog struct{}
func (d dog) say() {
fmt.Println("wangwang")
}
只要实现了say()这个方法的类型都可以称为sayer类型?
type sayer interface {
say() //参数列表和返回值列表的变量名可以省略
}
//调用打函数
func da(qwe sayer) {
qwe.say()
}
func main() {
cc := cat{}
da(cc)
dd := dog{}
da(dd)
//接口是一种类型,可以存储接口内部方法所拥有的类型
var s sayer
pp2 := person{"小王子"}
s = pp2
fmt.Println(s)
}
//接口的好处:添加结构体时同时添加同一个方法就可以使用接口
type person struct {
name string
}
func (p person) say() {
fmt.Println("a")
}
// 一个类型可以实现多个接口
// 多个类型可以实现相同的接口
//接口可以嵌套
type sayer interface {
say() //参数列表和返回值列表的变量名可以省略
}
type mover interface {
move()
}
type animal interface {
mover
sayer
}
func (p person) say() {//只用值接收者就好
fmt.Println("a")
}
func (p *person) say() {//多了个*
fmt.Println("a")
}
var x interface{}
x = "hello"
a, ok := x.(string) //会将"hello"赋值给a
fmt.Println(a) //直接输出"hello"
if !ok {
fmt.Printf("不是")
} else {
fmt.Println("是")
}
switch v := x.(type) {
case string:
fmt.Printf("是字符串类型,value:%39. 数组中出现次数超过一半的数字\n", v)
default:
fmt.Println("...", v)
}
//空接口是指没有定义任何方法的接口
//所以任何类型都实现了空接口
//所以空接口可以存储任意类型的变量
type x interface{} //一般用到的时候才定义
x = "hello"
x = 100
x = false
fmt.Println(x)
//空接口的应用
//1.空接口作为函数的参数:例如fmt.Println(x)
// Println(a ...interface{空})
//2.空接口作为map的value
var m = make(map[string]interface{}, 16)
m["asdf"] = "a"
m["qq"] = 12
m["aaa"] = []string{"aa", "qq"}
fmt.Println(m)
package main
import (
"errors"
"fmt"
"math"
)
func Sqrt(f float64) (float64, error) {
if f < 0 {
//return -1, errors.New("math: square root of negative number")
}
return math.Sqrt(f), nil
}
func main() {
result, err := Sqrt(-13)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(result)
}
}
原文:https://www.cnblogs.com/li-zi-feng/p/14350218.html