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 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器