【发布时间】:2015-03-16 07:00:07
【问题描述】:
如何将interface{} 转换为bytes.Buffer?
最小的example
package main
import (
"bytes"
"fmt"
)
func ToJson5(any interface{}) string {
if any == nil {
return `''`
}
switch any.(type) {
case bytes.Buffer: // return as is
return any.(bytes.Buffer).String()
// other types works fine
}
return ``
}
func main() {
x := bytes.Buffer{}
fmt.Println(ToJson5(x))
}
错误是:
main.go:14: cannot call pointer method on any.(bytes.Buffer)
main.go:14: cannot take the address of any.(bytes.Buffer)
当更改为bytes.Buffer{}(我认为不太正确)时,错误是:
main.go:13: bytes.Buffer literal (type bytes.Buffer) is not a type
main.go:14: bytes.Buffer literal is not a type
【问题讨论】:
-
通常该类型用作指针,所以通常
x := new(bytes.Buffer)但您也可以将它与&x一起使用(例如var x bytes.Buffer; fmt.Fprintln(&x, "Foo"))。你可能不想像你一样通过价值传递一个!然后您还可以使用case *bytes.Buffer和any.(*bytes.Buffer).String(),它们应该可以正常工作,因为您将在指针上调用指针方法。但是在icza的答案中使用v := any.(type)更容易。 -
@DaveC 请注意,尽管在这种情况下
any.(*bytes.Buffer).String()将不起作用,因为传递的值是 not 指针,因此您无法使用类型断言从中获取指针.仅当函数像这样调用时才有效:ToJson5(&x)). -
@icza,这就是为什么我还提到使用
&x并且按值传递bytes.Buffer是一个坏主意。注意我使用了“then”这个词。
标签: go type-conversion