英文:
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
好的,以下是翻译好的内容:
好的,有两件事情:
-
你没有“继承”
io.Writer
(你只是声明你的结构体包含一个写入器)。在Go语言中,接口是隐式的。如果你的结构体实现了Write(p []byte) (n int, err, error)
,它就是一个io.Writer
,可以在任何接受该接口的函数中使用。不需要声明任何东西。 -
至于你的问题:
fmt.Printf("%s\n", string(p))
英文:
Ok, two things:
-
You haven't "inherited"
io.Writer
(you simply stated that your struct contains a writer). In go, interfaces are implicit. If your struct implementsWrite(p []byte) (n int, err, error)
, it is anio.Writer
and can be used with any function accepting it. Period. No need to declare anything. -
As for your problem:
fmt.Printf("%s\n", string(p))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论