go中的type关键字
2020-05-04 本文已影响0人
多啦A梦的野比大雄
go中的type关键字用来标识类型。
“类型”可以是普通类型、复合类型,也可以自定义。
- 普通类型
boolean, int, string 等等。如
type Age int8
age := Age(8.00)
fmt.Println(age)
打印出
8
- 复合类型(struct, map, interface, pointer, function...)
- struct
type Book struct {
title string
author string
year string
isbn string
}
- interface
type ReadWrite interface {
read()
write(b []byte)
}
使用示例
package main
import (
"fmt"
"io/ioutil"
)
type File struct{
file string
}
type ReadWrite interface {
Read()
Write(b []byte)
}
func (f File) Read(){
data,err := ioutil.ReadFile(f.file)
if err != nil {
fmt.Println(err)
}
fmt.Println(string(data))
}
func (f File) Write(b []byte) {
ioutil.WriteFile(f.file, b, 0777)
}
func main() {
var reader=File{"data.txt"}
reader.Read()
reader.Write([]byte("this is added data"))
reader.Read()
}
打印出
this is test data
this is added data
type interface定义一个接口,实现了接口中的方法就继承了接口。