如何在Go语言中定义可变字段的结构体?

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

How can I define variadic fields on a struct? Go

问题

我需要一个数据结构,除了自定义字段之外,还可以接受名称/值对。我该如何定义这样的结构?

例如:

type mybasket struct {
    Coupons string
    Amount int
    ....... // string or int
}
英文:

I need a data structure which accepts name / value pairs in addition to custom fields. How can I define a such structure ?

e.g.

type mybasket struct {
    Coupons string
    Amount int
    ....... // string or int
}

答案1

得分: 5

我建议在类型上定义settergetter方法,并将值存储在结构体的切片中。

例如:

package main

import "fmt"

type kv struct {
    k, v string
}

type mybasket struct {
    Coupons  string
    Amount   int
    Contents []kv
}

func (t *mybasket) SetContents(c ...kv) {
    t.Contents = c
    return
}

func (t *mybasket) GetContents() []kv {
    return t.Contents
}

func main() {
    T := &mybasket{"couponlist", 100, []kv{}} // 新的购物篮
    kvs := []kv{{"foo", "bar"}, {"baz", "bat"}} // 内容
    T.SetContents(kvs...) // 设置内容
    fmt.Printf("%v", T.GetContents()) // 获取内容
}

输出结果:

[{foo bar} {baz bat}]

Playground

英文:

I'd recommend defining setter and getter methods on the type, and store the values in a slice in the struct.

For example:

package main

import "fmt"

type kv struct {
	k, v string
}

type mybasket struct {
	Coupons  string
	Amount   int
	Contents []kv
}

func (t *mybasket) SetContents(c ...kv) {
	t.Contents = c
	return
}

func (t *mybasket) GetContents() []kv {
	return t.Contents
}

func main() {
	T := &mybasket{"couponlist", 100, []kv{}} // New Basket
	kvs := []kv{{"foo", "bar"}, {"baz", "bat"}} // Contents
	T.SetContents(kvs...) // Set Contents
	fmt.Printf("%v", T.GetContents()) // Get Contents
}

Prints:

[{foo bar} {baz bat}]

Playground

huangapple
  • 本文由 发表于 2014年11月24日 12:50:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/27098062.html
匿名

发表评论

匿名网友

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

确定