我试图将一组键值传递给Go中的另一个函数。对Go来说很新,所以我很难弄明白。
package main
import(
"net/http"
"fmt"
"io/ioutil"
"net/url"
)
type Params struct {
items []KeyValue
}
type KeyValue struct {
key string
value string
}
func main() {
data := []Params{
KeyValue{ key: "title", value: "Thingy" },
KeyValue{ key: "body", value: "Testing 123" }}
response, error := makePost("test-api.dev", &data)
}
func makePost(urlString string, values []Params) (string, error) {
v := url.Values{}
for _, val := range values {
v.Add(val.key, val.value)
}
response, err := http.PostForm(urlString, v)
defer response.Body.Close()
contents, err := ioutil.ReadAll(response.Body)
if err != nil {
fmt.Printf("%s", err)
}
return string(contents), err
}
我收到错误:
val.key undefined (type Params has no field or method key)
val.value undefined (type Params has no field or method key)
然而,当我编译时。
去游乐场链接http://play.golang.org/p/CQw03wZmAV
提前致谢!
答案 0 :(得分:2)
values
是[]Params
。当您对其进行迭代时,val
将是Params
,但您将其视为KeyValue
。你真的想要传递一个[]Params
,而不只是一个Params
甚至一个[]KeyValue
吗?
答案 1 :(得分:1)
正如其他人提到的那样,您有一个[]Params
,但您正尝试使用KeyValue
进行初始化。
data := []Params{
KeyValue{ key: "title", value: "Thingy" },
KeyValue{ key: "body", value: "Testing 123" }}
相反,请尝试:
data := &Params{items: []KeyValue{
{key: "title", value: "Thingy"},
{key: "body", value: "Testing 123"},
}}
答案 2 :(得分:0)
谢谢大家,最后得到了它:http://play.golang.org/p/aCKU5bTnhT
package main
import (
"fmt"
)
type Params struct {
items []KeyValue
}
type KeyValue struct {
key string
value string
}
func main() {
data := Params{items: []KeyValue{
{key: "title", value: "Thingy"},
{key: "body", value: "Testing 123"},
}}
makePost("test-api.dev", data)
}
func makePost(urlString string, values Params) string {
for _, val := range values.items {
fmt.Println("%s", val.key+":"+val.value)
}
return string("test")
}