首页 \ 问答 \ 在具有接口{}值的地图上实现String()(Implement String() on a map with interface{} values)

在具有接口{}值的地图上实现String()(Implement String() on a map with interface{} values)

我怎么能写一个函数来在Go(Golang)中打印一个地图对象? 现在我有这个,但它没有编译。 它返回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)
}

我希望String()返回一个像hello: world\nfloating: 10.0\nwhole: 12\n这样的字符串hello: world\nfloating: 10.0\nwhole: 12\n 。 然后我可以传递给fmt.Println()来打印它。 在Java中,我会使用StringBuilder

hello: world
floating: 10.0
whole: 12

我也尝试使用case string:case float64 stringBuffer来切换value.(type) ,但后来我不知道如何将这些值写入stringBuffer


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\nfloating: 10.0\nwhole: 12\n. 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.


原文:https://stackoverflow.com/questions/24621768
更新时间:2020-03-23 22:27

最满意答案

这是一个惯用的解决方案。

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

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 + "\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()
}
2017-08-08

相关文章

更多

最新问答

更多
  • 如何避免MDIParent表单调整大小(How do I avoid MDIParent form from resizing)
  • Angular自定义指令调用另一个自定义指令(Angular custom directive calling another custom directive)
  • 如何通过参数将文本解析并附加到SQL Server 2005中的存储过程(How to Parse and Append text to a stored procedure in SQL Server 2005 via a parameter)
  • OpenCV中心Homography(OpenCV Center Homography)
  • 如何在linux shell脚本中计算日期-N?(How to calculate date -N in linux shell scripting?)
  • 如何使用Devise创建用户配置文件?(How Do I Create a User Profile With Devise?)
  • 清理模式以管理树上的多步异步过程(Clean pattern to manage multi-step async processes on a tree)
  • 场景的角色(Role of the Scene)
  • 组件中的Angular 2组件[重复](Angular 2 Component In Component [duplicate])
  • jsPlumb draggable element javascript函数(jsPlumb draggable element javascript function)
  • MVC4:ViewModel(带有radiobuttonlist)在HttpPost之后为空(MVC4: ViewModel (with radiobuttonlist) is empty after HttpPost)
  • 如何在同一帐户上设置“Dev repo”(在prod和团队之间)(How to set up a “Dev repo” (between the prod and the team) on the same account)
  • 如何在tcl中将eth0配置为发送方udp端口(how to configure eth0 as a sender udp port in tcl)
  • 如何使用预定义文本替换来自数据库的部分结果(How do I replace part of result coming from Database with predefined text)
  • Selenium Java注入了新的Javascript函数(Selenium Java inject new Javascript function)
  • 使用.on的多个下拉菜单选择文本仅适用于第一个下拉列表(Multiple Dropdowns Menu Selection text using .on works only on first dropdown)
  • 快速将黄土曲线添加到大型数据集图中的方法(Quick way to add loess curve to large data set graph)
  • FilteringSelect in mvc(FilteringSelect in mvc)
  • 在Delphi XE2中开发Mac或iOS应用程序需要哪些硬件/软件?(What hardware/software is necessary to develop Mac or iOS apps in Delphi XE2?)
  • 在原型的构造函数中初始化属性时获取“未定义”(Getting 'undefined' when a property is initialized in the constructor of a prototype)
  • 通过越狱加载的应用程序的Documents文件夹位置(Location of Documents folder for an app loaded via jailbreak)
  • 在OpenGL中使用可编程和固定管道功能(Using both programmable and fixed pipeline functionality in OpenGL)
  • 将任何用户输入重定向到单独的底层程序(redirect any user input to a separate underlying program)
  • 编辑文本不能正常工作android(Edit texts not working properly android)
  • “user_denied”Facebook应用页面上的Facebook用户区域设置(Facebook user locale on “user_denied” facebook app page)
  • 在大图像中找到小的部分透明图像的坐标(find coordinates of small partially-transparent image within a large image)
  • 我如何在cakephp 3.1中获得完整的相对路径?(How i can get full relative path of image in cakephp 3.1?)
  • 如何保存拖动标记的新本地化?(How to save new localization of dragged marker?)
  • MySQL UPDATE vs INSERT和DELETE(MySQL UPDATE vs INSERT and DELETE)
  • 在执行查询之前,在SQLAlchemy模型中将datetime转换为unix时间戳?(Convert datetime to unix timestamp in SQLAlchemy model before executing query?)