-2

I have struct, the structure like below:

package main

import "fmt"

type Data [][]struct {
    Message string `json:"message"`
    Status  string `json:"status"`
}

func main() {
    d := Data{
        {{message, "Halo"}, {status, "Active"}},
    }
    fmt.Println(d)
}

$ go run arr.go
# command-line-arguments
.\arr.go:12:5: undefined: message
.\arr.go:12:24: undefined: status

I want to get fields "Message" and "Status" to send back to the response. My question is How can I initialize the struct and accessing its fields? But I gon an error.

Ahmad Wijaya
  • 11
  • 1
  • 7
  • 1
    https://tour.golang.org/ – Adrian Dec 21 '20 at 17:41
  • If you are writing a single literal value, then the syntax is the same as if you were using a named struct type. If you ever want to `append` or insert any values however, I suggest you avoid the anonymous structs and just stick with the standard named types to avoid having to write the struct type out every time. – JimB Dec 21 '20 at 19:23
  • you may benefit from this https://stackoverflow.com/questions/39804861/what-is-a-concise-way-to-create-a-2d-slice-in-go – ygk Dec 21 '20 at 21:10

1 Answers1

0

this may help.

Note. my example is a 2x2 dimension, you can have any dimension.

package main

import "fmt"

type Data [][]struct {
    Message string `json:"message"`
    Status  string `json:"status"`
}

func main() {
    d := Data{
        {{"message1", "one"},{"message2", "two"}},
        {{"message3", "three"},{"message4", "four"}},
    }
    fmt.Println(d)
}

Output.

[[{message1 one} {message2 two}] [{message3 three} {message4 four}]]

  • Hai, Thank you in advance. If i try to make flow like this i got an error: package main import "fmt" type Data [][]struct { Message string `json:"message"` Status string `json:"status"` } func main() { d := Data{ {{message, "Halo"}, {status, "Active"}}, } fmt.Println(d) } – Ahmad Wijaya Dec 22 '20 at 00:44
  • the issue with "Data{ {{message, "Halo"}, {status, "Active"}}, }" is that you are creating message and status as separate instances, that's wrong. they should be initialized as one item. – Muriithi Derrick Dec 22 '20 at 05:56