【问题标题】:How to convert interface{} to bytes.Buffer如何将 interface{} 转换为 bytes.Buffer
【发布时间】: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.Bufferany.(*bytes.Buffer).String(),它们应该可以正常工作,因为您将在指针上调用指针方法。但是在icza的答案中使用v := any.(type)更容易。
  • @DaveC 请注意,尽管在这种情况下 any.(*bytes.Buffer).String() 将不起作用,因为传递的值是 not 指针,因此您无法使用类型断言从中获取指针.仅当函数像这样调用时才有效:ToJson5(&x)).
  • @icza,这就是为什么我还提到使用&x 并且按值传递bytes.Buffer 是一个坏主意。注意我使用了“then”这个词。

标签: go type-conversion


【解决方案1】:

您可以在Type switch 中使用Short variable declarationcase 分支中输入类型值:

switch v := any.(type) {
case bytes.Buffer: // return as is
    return v.String() // Here v is of type bytes.Buffer
}

Go Playground 上试试。

引用规范:

TypeSwitchGuard 可能包含一个简短的变量声明。当使用该形式时,变量在每个子句的隐式块的开头声明。在仅列出一种类型的 case 子句中,变量具有该类型;否则,变量具有 TypeSwitchGuard 中表达式的类型。

【讨论】:

  • 啊我明白了,我从来不知道这个XD
猜你喜欢
  • 1970-01-01
  • 2016-11-06
  • 2021-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-10
  • 2015-01-14
  • 2018-12-25
相关资源
最近更新 更多