Golang在引用子结构数组方面存在问题

huangapple go评论84阅读模式
英文:

Golang problems with referencing arrays of sub structures

问题

我遇到了一个问题,不知道如何引用子结构的元素。

参考:http://play.golang.org/p/pamS_ZY01s

给定以下代码...如何引用room结构中的数据?我尝试了fmt.Println(*n.Homes[0].Rooms[0].Size),但是不起作用。

代码示例如下:

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"

    // 初始化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)
}
英文:

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

得分: 4

首先,*[]Home 是非常浪费的。在底层,切片是一个由三个字组成的结构体,其中一个是指向数组的指针。你在这里引入了双重间接引用。这篇关于Go语言数据结构的文章非常有用。

现在,由于这种间接引用,你需要在每个指向切片的指针表达式中加上解引用运算符 *。像这样:

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

但是,实际上,只需去掉指针即可。

英文:

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.

huangapple
  • 本文由 发表于 2015年1月24日 06:22:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/28119707.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定