【问题标题】:Unpack slice to struct values将切片解包到结构值
【发布时间】:2020-10-10 23:30:13
【问题描述】:

假设你有这个结构,

type Color struct {
    R uint8
    G uint8
    B uint8
    A uint8
}

还有这个切片,

s := []uint8{50, 60, 100, 100}

有没有办法将切片“解包”到结构中? (例如使用扩展运算符或其他东西)

c := Color{s...}

我的意思不是这个,

c := Color{s[0], s[1], s[2], s[3]}

【问题讨论】:

  • Color{s[0], s[1], s[2], s[3]} 很好。 Color{R: s[0], G: s[1], B: s[2], A: s[3]} 会更好。

标签: go struct slice


【解决方案1】:

不幸的是,没有办法做到这一点。如果您想减少写作工作,可能有一种解决方法:

func NewColor(values ...uint8) Color {
   return Color {
    R: values [0], G: values [1], B: values [2], A: values [3],
   }
}

但是,除非您还添加了越界检查,否则这很危险。你可以添加这样的东西来防止它,但是它可能会给你留下错误的颜色:

if len(values) != 4 { 
   return Color {} 
}

然后您就可以按照您想要的方式创建颜色:

s := []uint8{50, 60, 100, 100}
color := NewColor(s...)

希望对你有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-12
    • 2019-06-09
    • 1970-01-01
    • 2018-06-05
    • 1970-01-01
    • 2019-04-12
    • 1970-01-01
    相关资源
    最近更新 更多