douliangbian7323 2015-01-23 22:22
浏览 3
已采纳

引用子结构数组的Golang问题

I am having a problem figuring out how to reference elements of a sub structure.

See: http://play.golang.org/p/pamS_ZY01s

Given something like following.... How do you reference data in the room struct? I have tried fmt.Println(*n.Homes[0].Rooms[0].Size), but that does not work.

Begin Code example

package main

import (
    "fmt"
)

type Neighborhood struct {
    Name  string
    Homes *[]Home
}

type Home struct {
    Color string
    Rooms *[]Room
}

type Room struct {
    Size string
}

func main() {
    var n Neighborhood
    var h1 Home
    var r1 Room

    n.Name = "Mountain Village"
    h1.Color = "Blue"
    r1.Size = "200 sq feet"

    // Initiaize Array of Homes
    homeslice := make([]Home, 0)
    n.Homes = &homeslice

    roomslice := make([]Room, 0)
    h1.Rooms = &roomslice

    *h1.Rooms = append(*h1.Rooms, r1)
    *n.Homes = append(*n.Homes, h1)

    fmt.Println(n)
    fmt.Println(*n.Homes)

}
  • 写回答

1条回答 默认 最新

  • duan198811 2015-01-23 22:30
    关注

    First, *[]Home is really wasteful. A slice is a three worded struct under the hood, one of them being itself a pointer to an array. You are introducing a double indirection there. This article on data structures in Go is very useful.

    Now, because of this indirection, you need to put the dereference operator * in every pointer-to-slice expression. Like this:

    fmt.Println((*(*n.Homes)[0].Rooms)[0].Size)
    

    But, really, just take out the pointers.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在不同的执行界面调用同一个页面
  • ¥20 基于51单片机的数字频率计
  • ¥50 M3T长焦相机如何标定以及正射影像拼接问题
  • ¥15 keepalived的虚拟VIP地址 ping -s 发包测试,只能通过1472字节以下的数据包(相关搜索:静态路由)
  • ¥20 关于#stm32#的问题:STM32串口发送问题,偶校验(even),发送5A 41 FB 20.烧录程序后发现串口助手读到的是5A 41 7B A0
  • ¥15 C++map释放不掉
  • ¥15 Mabatis查询数据
  • ¥15 想知道lingo目标函数中求和公式上标是变量情况如何求解
  • ¥15 关于E22-400T22S的LORA模块的通信问题
  • ¥15 求用二阶有源低通滤波将3khz方波转为正弦波的电路