Dictionary 在具有接口{}值的映射上实现String()
如何编写函数以在Go(Golang)中打印地图对象?现在我有这个,但它没有编译。它返回Dictionary 在具有接口{}值的映射上实现String(),dictionary,go,Dictionary,Go,如何编写函数以在Go(Golang)中打印地图对象?现在我有这个,但它没有编译。它返回无法将值(类型接口{})转换为类型反射。种类:需要类型断言 package main type MyDictionary map[string]interface{} func (d MyDictionary) String() string { var stringBuffer bytes.Buffer for key, value := range d { string
无法将值(类型接口{})转换为类型反射。种类:需要类型断言
package main
type MyDictionary map[string]interface{}
func (d MyDictionary) String() string {
var stringBuffer bytes.Buffer
for key, value := range d {
stringBuffer.WriteString(key)
stringBuffer.WriteString(": ")
valueType := reflect.Kind(value)
switch valueType {
case reflect.String:
log.Println("string") // just to check if this block gets executed
// Add to stringBuffer
case reflect.Float64:
log.Println("float64") // just to check if this block gets executed
// Add to stringBuffer
default:
log.Println("Error: type was", valueType)
}
}
return stringBuffer.String()
}
func main() {
var dict MyDictionary = make(MyDictionary)
dict["hello"] = "world"
dict["floating"] = 10.0
dict["whole"] = 12
fmt.Println(dict)
}
我希望String()
返回一个字符串,如hello:world\n loating:10.0\n hole:12\n
。然后我可以传递到fmt.Println()
以打印此文件。在Java中,我会使用StringBuilder
来实现这一点
hello: world
floating: 10.0
whole: 12
我还试着用
大小写字符串:
和大小写浮动64
打开值。(type)
,但是我不知道如何将这些值写入字符串缓冲区
您需要获取接口的类型,然后打开类型
valueType := reflect.TypeOf(value).Kind()
工作示例:
输出
2009/11/10 23:00:00 string
2009/11/10 23:00:00 Type was: float64
2009/11/10 23:00:00 Type was: int
hello: floating: whole:
这里有一个惯用的解决方案
func (d MyDictionary) String() string {
var buf bytes.Buffer
for k, v := range d {
buf.WriteString(k + ": ")
// v is an interface{} here
switch v := v.(type) {
// The inner v is typed. It shadows the outer interface{} v. That's
// the idiomatic part.
case string:
buf.WriteString(v + "\n") // v is a string
case int:
buf.WriteString(fmt.Sprintln(v)) // v is an int
case float64:
buf.WriteString(fmt.Sprintln(v)) // v is a float64
}
}
return buf.String()
}
您可以将其简化为以下内容(): 其中打印:
hello: world
floating: 10
whole: 12
floating: 10.00
whole: 12
hello: world
显然,“整”浮点已删除小数(如果您将其设置为10.5
,它将正确打印)。如果需要,那么您需要打开float
并指定精度():
其中打印:
hello: world
floating: 10
whole: 12
floating: 10.00
whole: 12
hello: world
也许我太含糊了。我希望
String()
返回一个字符串,该字符串将所有键和值连接到一个字符串,然后返回该字符串。
floating: 10.00
whole: 12
hello: world