亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在結構中聲明和使用映射

在結構中聲明和使用映射

Go
湖上湖 2023-07-31 11:00:17
我對 golang 非常菜鳥,幾天前才開始。實際上我正在嘗試做一個簡單的練習來習慣 golang 語法。我在 main.go 中有這個:package main import(    "fmt"    // "stringa"    "main/survey")func main() {    var questions = []survey.Question{        {            Label: "Quest?o 1",            Instructions : "Instru??o",            Options : {                1 : "Op1",                2 : "Op2",            },            Answer: {                1 : "Op1",            },        },    }    fmt.Println(questions[0].Label)}我嘗試制作一個簡單的結構,但我知道。如果我使用接口,問題就可以解決,但如果在接下來的步驟中,我將需要在結構中使用地圖......PS:這是我使用過的示例結構:package surveyimport(    // "fmt"    // "strings"    // "strconv")// This is a simple Question in a survey codetype Question struct {    // This is a label for the quetsion    Label string    // This is a instructions and is not required    Instructions string    // this is a multiple options answer    Options map[int]string    // this is a answer correct response    Answer map[int]string}最后的問題是:如何在結構內部的參數中使用映射并將其寫入聲明中?
查看完整描述

1 回答

?
白衣非少年

TA貢獻1155條經驗 獲得超0個贊

類型 ( map[int]string) 必須在結構體字段值的復合文字表達式中使用:


var questions = []survey.Question{

    {

        Label:        "Quest?o 1",

        Instructions: "Instru??o",

        Options: map[int]string{

            1: "Op1",

            2: "Op2",

        },

        Answer: map[int]string{

            1: "Op1",

        },

    },

}

復合文字表達式中的類型只能在切片元素(與 的元素一樣[]survey.Question)、映射鍵和映射值上被省略。


在 Go 游樂場上運行它。



查看完整回答
反對 回復 2023-07-31
  • 1 回答
  • 0 關注
  • 149 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號