英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论