golang: Getting string from []byte

huangapple go评论78阅读模式
英文:

golang: Getting string from []byte

问题

我是你的中文翻译助手,以下是翻译好的内容:

我是Go语言的新手(来自C++世界)。

我创建了一个新的写入器,它“继承”自io.Writer:

type httpWriter struct {
  io.Writer
}

接下来,我实现了io.Writer接口的Write()函数:

func (w *httpWriter) Write(p []byte) (n int, err error) {
  // 实现逻辑...
}

然后,我将所有输出重定向到该写入器。

我在Write()实现中遇到了打印实际字符串的问题。
我尝试了文档中能找到的所有字符串格式化方法,但没有一个能将原始字符串作为输出。

fmt.Printf("%s\n", p) // 等等...

希望能得到帮助。

英文:

I'm new to go (coming from the C++ world)

I've created a new writer, which "inherits" from io.writer:

type httpWriter struct {
  io.Writer
}

Next I've implemented the Write() function of the io.Writer interface:

func (w *httpWriter) Write(p []byte) (n int, err, error){...}

Then, I've redirected all output to that writer.

I'm having truble to print the actual string in the Write() implementation.
I've tried all string formatting I could find in the documentation, but none of them give me the original string as an output.

fmt.Printf("%s\n",p) \\etc..

Would appreciate assistance

答案1

得分: 5

好的,以下是翻译好的内容:

好的,有两件事情:

  1. 你没有“继承”io.Writer(你只是声明你的结构体包含一个写入器)。在Go语言中,接口是隐式的。如果你的结构体实现了Write(p []byte) (n int, err, error),它就是一个io.Writer,可以在任何接受该接口的函数中使用。不需要声明任何东西。

  2. 至于你的问题:fmt.Printf("%s\n", string(p))

英文:

Ok, two things:

  1. You haven't "inherited" io.Writer (you simply stated that your struct contains a writer). In go, interfaces are implicit. If your struct implements Write(p []byte) (n int, err, error), it is an io.Writer and can be used with any function accepting it. Period. No need to declare anything.

  2. As for your problem: fmt.Printf("%s\n", string(p))

huangapple
  • 本文由 发表于 2016年2月8日 03:07:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/35257784.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定