在单值上下文中的多值,没有返回函数。

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

multiple-value in single-value context no return func

问题

我在Go中有一个简单的函数,它只是向缓冲区写入内容。我没有在函数上设置返回类型,所以我不确定为什么会出现这个错误。这是我的代码:

func Write(buffer *bytes.Buffer, values ...string) {
  for _, val := range values {
    _, err := buffer.WriteString(val)
    if err != nil {
      // 打印错误
    }
  }
  _, err := buffer.WriteString(" ")
  if err != nil {
    // 打印错误
  }
}

我在两个调用buffer.WriteString的地方都遇到了问题。这让我相信它与缓冲区上的WriteString方法的返回类型有关,但我对Go的经验不足,无法确定。

如果有帮助,将不胜感激。

编辑:已更新的代码。

英文:

I have a func in Go that simply writes to a buffer. I have no return type set on the func so I am not sure why I am seeing this error. Here is my code:

func Write(buffer *bytes.Buffer, values ...string) {
  for _, val := range values
    _, err := *buffer.WriteString(val)
    if err != nil {
      // print error
    }
  }
  _, err := *buffer.WriteString(" ")
  if err != nil {
    // print error
  }
}

It complains at both lines where I have buffer.WriteString. This leads me to believe it has something to do with the return types of the WriteString method on the buffer but I am not experienced enough in Go to know for sure.

Any help would be appreciated.

Edit: Updated code.

答案1

得分: 1

在Go语言中,调用方法时不需要解引用指针。*操作符在buffer.WriteString之前是应用于返回的值。要解引用buffer,你需要写成(*buffer).WriteString,但实际上这并不需要:

func Write(buffer *bytes.Buffer, values ...string) {
    for _, val := range values {
        _, err := buffer.WriteString(val)
        if err != nil {
            // 打印错误
        }
    }
    _, err := buffer.WriteString(" ")
    if err != nil {
        // 打印错误
    }
}
英文:

You don't need to dereference pointers to call methods in Go. The * operator before buffer.WriteString is applied to the returned values. To dereference buffer you would need to write (*buffer).WriteString, but that's not needed at all:

func Write(buffer *bytes.Buffer, values ...string) {
	for _, val := range values {
		_, err := buffer.WriteString(val)
		if err != nil {
			// print error
		}
	}
	_, err := buffer.WriteString(" ")
	if err != nil {
		// print error
	}
}

huangapple
  • 本文由 发表于 2016年3月15日 05:28:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/35998455.html
匿名

发表评论

匿名网友

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

确定