这是我参与「第五届青训营 」伴学笔记创作活动的第2天
接口
在go中定义一个接口,语法格式如下
type 接口类型名 interface{
方法名1( 参数列表1 ) 返回值列表1
方法名2( 参数列表2 ) 返回值列表2
…
}
具体例子如下:
type AnimalIF interface {
Sleep()
GetColor() string
GetType() string
}
上述代码表示定义了一个名为AnimalIF的接口,接口定中定义了Sleep、GetColor、GetType三个方法,其中GetColor和GetType方法具有返回值,返回值类型为string,而Sleep方法没有返回值
实现接口
在go中实现一个接口,只需要一个类实现该接口中的所有方法,具体例子如下,以上文中的AnimalIF接口为例子:
type Cat struct {
color string
}
func (this *Cat) Sleep() {
fmt.Println("Cat sleep")
}
func (this *Cat) GetColor() string {
return this.color
}
func (this *Cat) GetType() string {
return "Cat"
}
上述代码中定义了一个Cat类,并实现了AnimalIF接口中的三个方法,这时就表明Cat实现了AnimalIF接口。
接口调用
首先我们定义一个AnimalIF指针,然后创建Cat类的对象,并让对象指向AnimalIF指针,再通过AnimalIF指针调用其中的方法;
func main() {
var animal AnimalIF //接口数据类型,一个父类指针
animal = &Cat{color: "orange"}
animal.Sleep() //调用的是car的sleep方法
fmt.Println(animal.GetColor())
fmt.Println(animal.GetType())
}
执行结果如下:
JSON操作
JSON的序列化操作,go官方有具体实现,我们使用时需要先引入对应的包
import (
"encoding/json"
)
定义一个类Movie,用于演示JSON相应操作
type Movie struct {
Title string `json:"title"`
Year int `json:"year"`
Price int `json:"rmb"`
Actors []string `json:"actors"`
}
并创建出类的对象,且对属性进行赋值
movie := Movie{
Title: "唐伯虎点秋香",
Year: 2000,
Price: 100,
Actors: []string{"lbw", "wnm"},
}
类-->json
调用Marshal方法,并将对象传入,方法返回转换好的json字符串和错误
//编码过程 struct=》json
jsonStr, err := json.Marshal(movie)
if err != nil {
fmt.Println("json marshal error", err)
return
}
fmt.Printf("jsonStr=%s\n", jsonStr)
//结果:{"title":"唐伯虎点秋香","year":2000,"rmb":100,"actors":["lbw","wnm"]}
json-->对象
调用Unmarshal方法,方法需要传入解码的字符串和接收属性的对象指针
//解码 json=》struct
m1 := Movie{}
object := json.Unmarshal(jsonStr, &m1)
if object != nil {
fmt.Println("json unmarshal error ", err)
return
}
fmt.Printf("%v", m1)