stringer接口
在print包下stringer
接口
// Stringer is implemented by any value that has a String method,
// which defines the ``native'' format for that value.
// The String method is used to print values passed as an operand
// to any format that accepts a string or to an unformatted printer
// such as Print.
type Stringer interface {
String() string
}
这个接口,类似于Java中重写通tostring方法.
对mook.Retriever
结构实现Stringer接口:
package mook
import "fmt"
type Retriever struct {
Contents string
}
func (r *Retriever) String() string {
return fmt.Sprintf("Retriever{Contents=%v}", r.Contents)
}
func (r *Retriever) Post(url string, params map[string]string) string {
r.Contents = params["contents"]
return "ok"
}
func (r *Retriever) Get(url string) string {
return r.Contents
}
func main() {
retriever := &mook.Retriever{"this is a fake imooc.com"}
var r Retriever = retriever
fmt.Println(r)
r= real2.Retriever{
UserAgent:"Mozilla/5.0",
TimeOut:time.Minute,
}
fmt.Println(r)
}
打印:
Retriever{Contents=another a fake imooc.com}
{Mozilla/5.0 1m0s}
mook.Retriever实现了stringer接口,已自定义形式答应.real2.Retriever没有实现stringer接口,所以默认打印形式.
read、write接口
read,write接口有很多用处,比如我们之前Golang学习笔记二中学习if判断语句中,写的printFile
函数,其实这里的file类就是实现了read和write接口,所以其实此时,我们使用read接口作为参数,拓展性会更好.
改造之后:
func printFile(filename string) {
file, e := os.Open(filename)
if e != nil {
panic(e)
}
printContentFile(file)
}
func printContentFile(reader io.Reader) {//使用reader接口作为参数
scanner := bufio.NewScanner(reader)
for scanner.Scan() {
println(scanner.Text())
}
}
当我们使用reader接口作为参数后,就不止打印文件内的信息,还可以打印字符串:
func main() {
printFile("basic/adc.txt")
println("---------")
s:=`asd
sss
www
111
1` //使用``框起来的字符串,可以做出换行与引号的字符串
printContentFile(strings.NewReader(s))
//forever()
}
打印:
asdd
1111
cccc
wqwe
---------
asd
sss
www
111
1
作者所有的学习源码在 go学习源码github地址,如果觉得有用的话帮小智贡献一个star😁