duanmei1885
2016-02-07 19:07
浏览 926
已采纳

golang:从[] byte获取字符串

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
",p) \\etc..

Would appreciate assistance

图片转代码服务由CSDN问答提供 功能建议

我是新手(来自C ++世界)

我创建了一个新的作家,它是从io.writer继承的:

  type httpWriter struct {
 io.Writer 
} 
  <  / pre> 
 
 

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

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

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

我很难在Write()实现中打印实际的字符串。 我尝试了我在文档中可以找到的所有字符串格式,但是没有一个给我原始字符串作为 输出。

  fmt.Printf(“%s 
”,p)\\ etc .. 
   
 
 

非常感谢您的帮助

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douci1615 2016-02-07 19:16
    已采纳

    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 ", string(p))

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题