簡體   English   中英

如何使用GO建立結構圖並將值附加到結構圖?

[英]How to build a map of struct and append values to it using GO?

我嘗試了許多方法來構建struct映射並向其附加值,但沒有找到任何方法。

地圖的鍵是字符串。 該結構由兩部分組成:“ x”整數和“ y”字符串切片。

我在構建地圖時遇到的錯誤是(for m): main.go:11: syntax error: unexpected comma, expecting semicolon, newline, or }

當我嘗試向地圖添加新的鍵和值時,錯誤為: go:33: syntax error: missing operand

非常感謝您幫助我發現錯誤!

package main

import "fmt"

type TEST struct {
    x  int
    y []string  
}

// none of these var gives the expected result

var m = map[string]*struct{x int, y []string}{"foo": {2, {"a", "b"}}, }

var m2 = map[string]struct{x int, y []string}{"foo": {2, {"a", "b"}}, }


var n = map[string]*struct{x int
            y []string
            }{"foo": {2, {"a", "b"}}, }

var o = map[string]*struct{
            x int
            y []string
            }{"foo": {2, {"a", "b"}}, }         



func main() {

    m["foo"].x = 4
    fmt.Println(m["foo"].x)

// how can I had a new key ?

    m["toto"].x = 0
    m["toto"] = {0, {"c", "d"}}

// and append the string "e" to {"c", "d"} ?

    m["toto"].y = append(m["toto"].y, "e")


    a := new(TEST)
    a.x = 0
    a.y = {"c", "d"}

    m["toto"] = a

    fmt.Println(m) 

}

這是一種編寫方法:

package main

import "fmt"


type TEST struct {
    x   int
    y   []string  
}

var m = map[string]*TEST { "a": {2, []string{"a", "b"}} }


func main() {

    a := new(TEST)
    a.x = 0
    a.y = []string{"c", "d"}

    m["toto"] = a

    fmt.Println(m) 

}

注意:兩種類型不一樣,只是因為它們的結構具有相同的字段。

很長的故事。 如果出於某種原因您更喜歡未命名的類型,則您在描述類型和值的復合文字中必須非常冗長

var m = map[string]*struct {
    x int
    y []string
}{"foo": {2, []string{"a", "b"}}}

或帶有分號

var m = map[string]*struct {x int; y []string}{"foo": {2, []string{"a", "b"}}}

並且沒有間接

var m1 = map[string]struct {
    x int
    y []string
}{2, []string{"a", "b"}}}

添加新密鑰

m["todo"] = &struct {
        x int
        y []string
    }{0, []string{"c", "d"}}

您還可以分配TEST結構,但只能分配無間接值,因為指針* TEST和* youunnamedstruct不可分配,但是具有相同字段可自行分配的結構

m1["todo"] = TEST{0, []string{"c", "d"}}

您只能附加到間接映射結構字段

m["todo"].y = append(m["todo"].y, "e")

因為直接映射結構字段不可尋址

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM