Go lang is it possible to create a struct that can also be used as a slice?

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

Go lang is it possible to create a struct that can also be used as a slice?

问题

在Go语言中,结构体(struct)不能直接作为切片(slice)来访问。但是,你可以在结构体中包含一个切片字段,然后通过该字段来访问切片元素。以下是你提供的示例代码的修改版本:

type Item struct {
    Name string
}

type ItemList struct {
    PackDate time.Time
    Items    []Item
}

然后,你可以通过切片索引来访问ItemList中的Item:

myItemList.Items[0].Name

你也可以通过结构体字段来访问ItemList的其他成员:

myItemList.PackDate

如果你想在Go中处理带有元数据的切片,可以使用结构体来包装切片和元数据字段。这是一种常见的模式,可以根据你的具体需求进行扩展和定制。

英文:

Is it possible to have a struct in go that can also be accessed as a slice?
So, for example, I'd want something like this:

type Item struct {
    Name string
}

type ItemList struct {
    PackDate time.Time
    []Item
}

And then I could access an Item in the ItemList as a slice.

myItemList[0].Name  

Or access the members of ItemList in the normal struct way.

myItemList.PackDate

If this is not possible, are there any recommended patterns for handling a sort of slice with metadata like this in go?

答案1

得分: 4

推荐的做法是将切片作为结构字段进行访问:

type Item struct {
    Name string
}

type ItemList struct {
    PackDate time.Time
    Items    []Item
}

访问值:

myItemList.Items[0].Name
myItemList.PackDate

遍历切片:

for _, item := range myItemList.Items {
    // 使用 item.Name 做一些操作
}
英文:

The recommended thing to do is to simply access the slice as a struct field:

type Item struct {
    Name string
}

type ItemList struct {
    PackDate time.Time
    Items    []Item
}

Accessing the values:

myItemList.Items[0].Name
myItemList.PackDate

Iterating over the slice:

for _, item := range myItemList.Items {
    // do something with item.Name
}

答案2

得分: 0

例如,

package main

import (
	"fmt"
	"time"
)

type Item struct {
	Name string
}

type ItemList struct {
	PackDate time.Time
	Items    []Item
}

func main() {
	list := ItemList{
		PackDate: time.Now(),
		Items:    []Item{{Name: "John"}, {Name: "Jane"}},
	}
	fmt.Println(list)
	fmt.Println(list.PackDate)
	fmt.Println(list.Items[1].Name)
}

输出:

{2009-11-10 23:00:00 +0000 UTC [{John} {Jane}]}
2009-11-10 23:00:00 +0000 UTC
Jane
英文:

For example,

package main

import (
	"fmt"
	"time"
)

type Item struct {
	Name string
}

type ItemList struct {
	PackDate time.Time
	Items    []Item
}

func main() {
	list := ItemList{
		PackDate: time.Now(),
		Items:    []Item{{Name: "John"}, {Name: "Jane"}},
	}
	fmt.Println(list)
	fmt.Println(list.PackDate)
	fmt.Println(list.Items[1].Name)
}

Output:

{2009-11-10 23:00:00 +0000 UTC [{John} {Jane}]}
2009-11-10 23:00:00 +0000 UTC
Jane

huangapple
  • 本文由 发表于 2017年6月7日 22:22:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/44415349.html
匿名

发表评论

匿名网友

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

确定