Home > Mobile >  How can I dereference the struct of this pointer
How can I dereference the struct of this pointer

Time:08-18

I've the below code using Google Map Matrix:

package main

import (
    "context"
    "fmt"
    "log"
    "time"

    "github.com/kr/pretty"
    "googlemaps.github.io/maps"
)

func main() {
    api_key := "xxxxxxx"
    c, err := maps.NewClient(maps.WithAPIKey(api_key))
    if err != nil {
        log.Fatalf("fatal error: %s", err)
    }

    r := &maps.DistanceMatrixRequest{
        Origins:      []string{"Dammam"},
        Destinations: []string{"Riyadh"},
        ArrivalTime:  (time.Date(1, time.September, 1, 0, 0, 0, 0, time.UTC)).String(),
    }

    resp, err := c.DistanceMatrix(context.Background(), r)
    if err != nil {
        log.Fatalf("fatal error: %s", err)
    }

    pretty.Println(resp)
}

And getting the output as:

&maps.DistanceMatrixResponse{
    OriginAddresses:      {"Dammam Saudi Arabia"},
    DestinationAddresses: {"Riyadh Saudi Arabia"},
    Rows:                 {
        {
            Elements: {
                &maps.DistanceMatrixElement{
                    Status:            "OK",
                    Duration:          14156000000000,
                    DurationInTraffic: 0,
                    Distance:          maps.Distance{HumanReadable:"410 km", Meters:409773},
                },
            },
        },
    },
}

From the output above, I need to print the Duration and the Distance.HumanReadable, i.e. I need to get: 14156000000000 and 410 km

So I can convert the trip duration to hrs and minutes as:

   value := 14156000000000 // value is of type int
    d2 := time.Duration(value)

    hr := int64(d2 / time.Hour)
    min := int64(d2 / time.Minute)
    m := min - hr*60
    fmt.Printf("Time required is: %d H and %d M", hr, m)

I tried:

    x := resp.Rows[0].Elements
    fmt.Println("Duration:", x)

But the output was:

Duration: [0xc000192840]

CodePudding user response:

resp.Rows[0].Elements is a slice ([]*DistanceMatrixElement) so you will need to specify which element you wish to output. I'd guess that you want:

x := resp.Rows[0].Elements[0].Duration
fmt.Println("Duration:", x)

playground

  •  Tags:  
  • go
  • Related