我正在嘗試將一組鍵、值傳遞給 Go 中的另一個函數(shù)。對 Go 非常陌生,所以我正在努力弄清楚。package mainimport( "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提前致謝!
3 回答

肥皂起泡泡
TA貢獻1829條經(jīng)驗 獲得超6個贊
values
是一個[]Params
。當您迭代它時,val
將是 a Params
,但您將其視為KeyValue
. 你真的想通過 an []Params
,而不是僅僅傳遞aParams
甚至只是 a[]KeyValue
嗎?

慕俠2389804
TA貢獻1719條經(jīng)驗 獲得超6個贊
正如其他人所提到的,您有一個[]Params但您正在嘗試使用KeyValues進行初始化。
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"},
}}
- 3 回答
- 0 關(guān)注
- 197 瀏覽
添加回答
舉報
0/150
提交
取消