英文:
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
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论