dtu11716 2014-10-04 12:40
浏览 46
已采纳

Println打印方括号,但接口不是切片

I'm having a strange problem with interfaces, when I try to print a value Println adds square brackets. I believe this is because that interface contains slices, but I'm not sure how should iterate them.

I'm quite sure it's a newbie question but I spend alot time searching for a clue and can't find any.

Also I couldn't reproduce it without using goes, so here's the code that I actually used:

package main


import "fmt"
import "github.com/belogik/goes"
import "net/url"

func getConnection() (conn *goes.Connection) {
    conn = goes.NewConnection("localhost", "9200")

    return
}

func main() {

    conn := getConnection()
    var query = map[string]interface{}{
        "query": map[string]interface{}{
            "bool": map[string]interface{}{
                "must": map[string]interface{}{
                    "match_all": map[string]interface{}{},
                },
            },
        },
        "from": 0,
        "size": 3,
        "fields": []string{"name"},
    }
    extraArgs := make(url.Values)
    searchResults, err := conn.Search(query, []string{"myindex"}, []string{"mytype"}, extraArgs)

    if err != nil {
        panic(err)
    }

    result := searchResults.Hits.Hits

    for _,element := range result {
        name := element.Fields["name"]
        fmt.Println( name )
        fmt.Printf( "%#v
", name )
    }
}

This outputs:

[One]
[]interface {}{"One"}
[Two]
[]interface {}{"Two"}
[Three]
[]interface {}{"Three"}

However if I try to loop over the "name" like so:

for _, e := range name {
    fmt.Println( e )
}

I'm getting "cannot range over name (type interface {})"

  • 写回答

1条回答 默认 最新

  • drb88830 2014-10-04 13:49
    关注

    Use a type assertion. For example,

    package main
    
    import "fmt"
    
    func main() {
        m := map[string]interface{}{}
        m["name"] = []interface{}{"One"}
        fmt.Println(m)
    
        name := m["name"]
        fmt.Println(name)
        fmt.Printf("%#v
    ", name)
    
        for _, e := range name.([]interface{}) {
            fmt.Println(e)
        }
    }
    

    Output:

    map[name:[One]]
    [One]
    []interface {}{"One"}
    One
    

    The Go Programming Language Specification

    Type assertions

    For an expression x of interface type and a type T, the primary expression

    x.(T)
    

    asserts that x is not nil and that the value stored in x is of type T. The notation x.(T) is called a type assertion.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算