• golang获取io.Reader对象 继承与实现


    很多时候比如

    net.http.Post

    会提示我们需要一个 io.Reader 对象,将字符串或者map或者struct或者文件内容是如何转为 io.Reader 对象 ?

    一、io.Reader 对象是一个抽象接口

    type Reader interface {
        Read(p []byte) (n int, err error)
    }

    任何它的实现的对象我们都可以传递进去

    二、它的实现有哪些

    1、bytes.Buffer 

    从字符串中创建 bytes.Buffer 对象的方式

    var test = bytes.NewBuffer([]byte("hello world"))

    2、strings.Reader

    从字符串创建该对象的方式

    strings.NewReader("hello world")

    引发了一个思考,golang的继承和实现是如何定义的:

    写个小Demo复习一下

    package main
    
    func main() {
    
        // 继承
        // Cat 是抽象接口
        // BigCat 也是抽象接口
        // 且BigCat 继承了 Cat (拥有Cat待实现的方法 Eat)
    
        // 实现
        // ActualCat 实现了 Cat 的所有func - ActualCat 实现的抽象接口 Cat
        // BigActualCat 实现了 BigCat的所有func - BigActualCat 实现了抽象接口 BigCat
    
        c := new(ActualCat)
        c.Eat("hello")
    
        d := new(BigActualCat)
        d.Eat("hello")
        d.Sleep("world")
    
        e := new(BlackCat)
        e.ActualCat.Eat("hello")
        e.B.Eat("world")
    }
    
    // Cat 抽象接口
    type Cat interface {
        Eat(n string) []byte
    }
    
    // BigCat 抽象接口
    type BigCat interface {
        // Cat 继承了一个抽象接口 - 要实现此接口就要把继承来的接口也实现
        Cat
        Sleep(n string) []byte
    }
    
    // ActualCat Cat抽象接口的实现
    type ActualCat struct {
    }
    
    func (a *ActualCat) Eat(n string) []byte {
        return []byte(n)
    }
    
    // BigActualCat 抽象接口的实现 - 实现了哪个取决于它是否实现了对应抽象接口的所有func
    type BigActualCat struct {
    }
    
    func (a *BigActualCat) Eat(n string) []byte {
        return []byte(n)
    }
    
    func (a *BigActualCat) Sleep(n string) []byte {
        return []byte(n)
    }
    
    // BlackCat 多重继承 - 继承了ActualCat也继承了 BigActualCat
    type BlackCat struct {
        *ActualCat
        B *BigActualCat
    }
    
    func (a *BlackCat) Say() {
    
    }
  • 相关阅读:
    完善例题3.2的日期类mydate
    杨辉三角形
    求100以内的素数
    九九乘法表
    实现计算机界面
    完善3.2例题
    杨辉三角法
    素数程序
    九九乘法表
    杨辉三角
  • 原文地址:https://www.cnblogs.com/xuweiqiang/p/16252409.html
Copyright © 2020-2023  润新知