3

I have a dynamic multi dimension array, I need to fill dynamically from the loop. how can i define the array and fill the data.

Here is the code which im trying

var arrDetails[][]string
var index int = 0
for _, orderdetails := range ordersfromdb {
    arrDetails[index]["OrderNumber"] = "001"
    arrDetails[index]["customernum"] = "cust_001"
    arrDetails[index]["orderstatus"] = "open"
    arrDetails[index]["orderprice"] = "200"
    index++
}

error which im facing:

non-integer slice index "OrderNumber"
non-integer slice index "customernum"
non-integer slice index "orderstatus"
non-integer slice index "orderprice"

I have done the same in php and works perfect:

for ($i=0;$i<5:$i++)
{
     $arr_orderdetails[$i]["OrderNumber"] = "001";
     $arr_orderdetails[$i]["customernum"] = "cust_001";
     $arr_orderdetails[$i]["orderstatus"] = "open";
     $arr_orderdetails[$i]["orderprice"] = "200";
}

I'm new to golang, not able to find where it is going wrong, any help much appreciated.

Thanks :)

5
  • Slices are indexed using integer numbers, and you used a string value. That obviously won't work. Maybe what you want is a slice of maps []map[string]float64 or a slice of structs describing your object? Commented Oct 16, 2018 at 8:56
  • how does your data look like, minimal example would help. Commented Oct 16, 2018 at 8:57
  • "I'm very new to [Go]" So take The Tour of Go and start with the simpler things until you are comfortable with them and jump into dynamic multidimensional stuff later. Commented Oct 16, 2018 at 9:01
  • nilsocket i have updated with sample data Commented Oct 16, 2018 at 9:26
  • "not able to find where it is going wrong" You cannot use strings as slice indices in Go. Go is neither PHP nor JavaScript. You should try a map. Commented Oct 16, 2018 at 9:28

4 Answers 4

2

Let's consider this solution:

arrDetails := map[int]map[string]string{}

index := 0
for _, orderdetails := range ordersfromdb {
    arrDetails[index] = map[string]string{} // you have to initialize map

    arrDetails[index]["OrderNumber"] = "001"
    arrDetails[index]["customernum"] = "cust_001"
    arrDetails[index]["orderstatus"] = "open"
    arrDetails[index]["orderprice"] = "200"

    index++
}

To convert results to json (as I saw you question in comment to @liao yu's answer), we should learn something more about tags:

import (
    "encoding/json"
    "fmt"
)

type OrderDetails struct {
    Number   string `json:"number"`
    Customer string `json:"customer"`
    Status   string `json:"status"`
    Price    string `json:"price"`
}

func main() {
    ordersfromdb := []int{1, 2, 3}

    var arrDetails []OrderDetails
    for _, v := range ordersfromdb {
        arrDetails = append(arrDetails, OrderDetails{
            Number:   fmt.Sprintf("order_number_%v", v),
            Customer: fmt.Sprintf("customer_%v", v),
            Status:   fmt.Sprintf("order_status_%v", v),
            Price:    fmt.Sprintf("$%v", v),
        })
    }

    data, err := json.Marshal(arrDetails)
    if err != nil {
        panic(err)
    }
    fmt.Println(string(data))
}

See it on playground: https://play.golang.org/p/IA0G53YX_dZ

Sign up to request clarification or add additional context in comments.

Comments

0

As per volker suggestion in the comment, I'm fill the multi dimensional array as below

arrDetails[index][0] = "001"
arrDetails[index][1] = "cust_001"
arrDetails[index][2] = "open"
arrDetails[index][3] = "200"

Comments

0

you can try this:

import "fmt"

func main() {

    var arrDetails []map[string]string
    var index int = 0

    //for _, orderdetails := range ordersfromdb {
    for i:=0; i<5;i++ {
        detail := make(map[string]string)

        detail["OrderNumber"] = "001"
        detail["customernum"] = "cust_001"
        detail["orderstatus"] = "open"
        detail["orderprice"] = "200"
        arrDetails = append(arrDetails, detail)

        index++
    }
    fmt.Printf("Hello, playground %+v", arrDetails )
}

1 Comment

can we covert the result to json? json.Marshal?
0

As you defined here your arrDetails variable as multidimentional slice as [][]string.It means you can not assign a string into its keys while you can assign string as a value.

You can do your code like below I mentioned.

package main

import (
    "fmt"
)

func main() {
  var arrDetails [][]string
  var s []string
  var index int
  for i:=0; i<5;i++ {
     s = []string{"001", "cust_001", "open", "200"}
     arrDetails = append(arrDetails, s)
     index++
  } 
fmt.Printf("Hello, playground %+v", arrDetails )
}

Or if you want keys and value pair then you've to use map as:

var arrDetails map[string]string

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.