简体   繁体   中英

How can I dereference the struct of this pointer

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 , ie 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]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM