gpt4 book ai didi

go - Println 打印方括号但接口(interface)不是 slice

转载 作者:IT王子 更新时间:2023-10-29 02:24:17 24 4
gpt4 key购买 nike

我遇到一个奇怪的接口(interface)问题,当我尝试打印一个值时,Println 添加了方括号。我相信这是因为该接口(interface)包含 slice ,但我不确定应该如何迭代它们。

我很确定这是一个新手问题,但我花了很多时间寻找线索,但找不到任何线索。

此外,如果不使用 goes,我无法重现它,所以这是我实际使用的代码:

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\n", name )
}
}

这个输出:

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

但是,如果我尝试像这样遍历“名称”:

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

我收到“无法覆盖名称范围(类型接口(interface) {})”

最佳答案

使用类型断言。例如,

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\n", name)

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

输出:

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.

关于go - Println 打印方括号但接口(interface)不是 slice ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26192922/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com