V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
yunshangdetianya
V2EX  ›  Go 编程语言

bytes.Buffer 包的疑惑

  •  
  •   yunshangdetianya · 2022-04-21 18:11:38 +08:00 · 1327 次点击
    这是一个创建于 738 天前的主题,其中的信息可能已经有所发展或是发生改变。

    bytes.Buffer 包的疑惑 请教各位一个问题,bytes.Buffer 包,在使用 bytes.NewBuffer 时候是如何调用到这个 func (b *Buffer) String() string 这个方法呢? 因为看源码 bytes.NewBuffer 要求传入一个[]byte 类型,返回一个 Buffer 类型,这个是如何调用到 String()这个方法,把[]byte 转换为 string 的呢? s1 是一个字符串类型 s2 := ([]byte(s1)) x := bytes.NewBuffer(s2) fmt.Println(x) //显示出来是字符串,肯定是上面方法的作用,但是不知道是如果调用的 研究了半天,可能是我太菜,所以来请教各位

    4 条回复    2022-04-21 18:49:17 +08:00
    yyf1234
        1
    yyf1234  
       2022-04-21 18:29:07 +08:00 via iPhone
    fmt 提供了 String()这个接口,bytes.Buffer 实现了这个接口,Println 时就会自动调用
    keepeye
        2
    keepeye  
       2022-04-21 18:37:52 +08:00
    One of the most ubiquitous interfaces is Stringer defined by the fmt package.

    type Stringer interface {
    String() string
    }
    A Stringer is a type that can describe itself as a string. The fmt package (and many others) look for this interface to print values.
    yunshangdetianya
        3
    yunshangdetianya  
    OP
       2022-04-21 18:48:37 +08:00
    @yyf1234 感谢回答
    yunshangdetianya
        4
    yunshangdetianya  
    OP
       2022-04-21 18:49:17 +08:00
    @keepeye thanks
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3199 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 12:27 · PVG 20:27 · LAX 05:27 · JFK 08:27
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.