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 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!