doxzrb8721 2014-11-24 04:50
浏览 10

如何在结构上定义可变参数字段? 走

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条回答 默认 最新

  • douben7493 2014-11-24 06:04
    关注

    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

    评论

报告相同问题?

悬赏问题

  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败