Golang中指针解引用的用法详解

Golang中指针解引用的用法详解 我使用以下Google地图矩阵代码:

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)
}

得到的输出如下:

&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},
                },
            },
        },
    },
}

根据上面的输出,我需要打印 DurationDistance.HumanReadable,即: 我需要获取:14156000000000410 km

这样我就可以将行程时长转换为小时和分钟,如下所示:

   value := 14156000000000 // value 是 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)

我尝试了:

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

但输出结果是:

Duration: [0xc000192840]

更多关于Golang中指针解引用的用法详解的实战教程也可以访问 https://www.itying.com/category-94-b0.html

2 回复

你收到 Duration: [0xc000192840] 是因为你收到的是一个指针,只需访问字段即可获取值。

你可以在测试文件中看到:

// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package maps

import (
	"context"
	"reflect"
	"testing"

更多关于Golang中指针解引用的用法详解的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


在Go语言中,指针解引用需要使用*操作符。根据你的代码,resp.Rows[0].Elements返回的是指针切片,你需要先解引用指针才能访问结构体字段。

以下是正确的解引用方式:

// 获取第一个元素的指针
elementPtr := resp.Rows[0].Elements[0]

// 解引用指针访问Duration字段
duration := elementPtr.Duration

// 解引用指针访问Distance结构体的HumanReadable字段
distance := elementPtr.Distance.HumanReadable

// 打印结果
fmt.Printf("Duration: %v\n", duration)
fmt.Printf("Distance: %s\n", distance)

// 转换时长
d2 := time.Duration(duration)
hr := int64(d2 / time.Hour)
min := int64(d2 / time.Minute)
m := min - hr*60
fmt.Printf("Time required is: %d H and %d M\n", hr, m)

或者使用更简洁的方式直接访问:

// 直接访问而不使用中间变量
duration := resp.Rows[0].Elements[0].Duration
distance := resp.Rows[0].Elements[0].Distance.HumanReadable

fmt.Printf("Duration: %v\n", duration)
fmt.Printf("Distance: %s\n", distance)

// 时长转换
d2 := time.Duration(duration)
hr := int64(d2 / time.Hour)
min := int64(d2 / time.Minute)
m := min - hr*60
fmt.Printf("Time required is: %d H and %d M\n", hr, m)

如果你想遍历所有元素(虽然这里只有一个):

for _, element := range resp.Rows[0].Elements {
    duration := element.Duration
    distance := element.Distance.HumanReadable
    
    fmt.Printf("Duration: %v\n", duration)
    fmt.Printf("Distance: %s\n", distance)
    
    // 时长转换
    d2 := time.Duration(duration)
    hr := int64(d2 / time.Hour)
    min := int64(d2 / time.Minute)
    m := min - hr*60
    fmt.Printf("Time required is: %d H and %d M\n", hr, m)
}

关键点说明:

  1. resp.Rows[0].Elements[0] 返回的是 *maps.DistanceMatrixElement 指针
  2. Go语言中,当通过指针访问结构体字段时,编译器会自动解引用,所以可以直接使用 element.Duration 而不需要 (*element).Duration
  3. 你之前打印 x 得到的是内存地址 [0xc000192840],因为打印的是指针切片本身,而不是解引用后的值

输出结果将是:

Duration: 14156000000000
Distance: 410 km
Time required is: 3 H and 55 M
回到顶部