duanping5306 2014-07-07 23:58
浏览 42
已采纳

在具有interface {}值的地图上实现String()

How could I write a function to print a map object in Go (Golang)? Right now I have this, but it doesn't compile. It returns cannot convert value (type interface {}) to type reflect.Kind: need type assertion.

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)
}

I want String() to return a string like hello: world floating: 10.0 whole: 12 . That I can then pass to fmt.Println() to print this. In Java, I would use StringBuilder for this.

hello: world
floating: 10.0
whole: 12

I also tried switching on value.(type) with case string: and case float64, but then I didn't know how to write those values to stringBuffer.

  • 写回答

3条回答 默认 最新

  • dqqn32019 2014-07-08 00:27
    关注

    Here's an idiomatic solution.

    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 + "
    ") // 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()
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值