bytes.Buffer 包的疑惑

2022-04-21 18:11:38 +08:00
 yunshangdetianya

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) //显示出来是字符串,肯定是上面方法的作用,但是不知道是如果调用的 研究了半天,可能是我太菜,所以来请教各位

1351 次点击
所在节点    Go 编程语言
4 条回复
yyf1234
2022-04-21 18:29:07 +08:00
fmt 提供了 String()这个接口,bytes.Buffer 实现了这个接口,Println 时就会自动调用
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
2022-04-21 18:48:37 +08:00
@yyf1234 感谢回答
yunshangdetianya
2022-04-21 18:49:17 +08:00
@keepeye thanks

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/848412

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX