[英]Unpack slice to struct values
Let's say that you have this struct,假设你有这个结构,
type Color struct {
R uint8
G uint8
B uint8
A uint8
}
And this slice,而这片,
s := []uint8{50, 60, 100, 100}
Is there a way to "unpack" the slice to the struct?有没有办法将切片“解包”到结构中? (Like with a spread operator or something) (例如使用扩展运算符或其他东西)
c := Color{s...}
Instead of this I mean,我的意思不是这个,
c := Color{s[0], s[1], s[2], s[3]}
Unfortunately there is no way to do this.不幸的是,没有办法做到这一点。 In case you want to reduce your writing work, there could be a workaround:如果您想减少写作工作,可能有一种解决方法:
func NewColor(values ...uint8) Color {
return Color {
R: values [0], G: values [1], B: values [2], A: values [3],
}
}
However this is dangerous unless you also add checks for out-of-bounds.但是,这很危险,除非您还添加了越界检查。 You could add something like this to prevent it, however it might leave you with a wrong color then:你可以添加这样的东西来防止它,但是它可能会给你留下错误的颜色:
if len(values) != 4 {
return Color {}
}
You can then just create the color with the way you wanted:然后,您可以按照您想要的方式创建颜色:
s := []uint8{50, 60, 100, 100}
color := NewColor(s...)
Hope that helps you.希望对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.