更新时间:2022-06-23 22:49:19
使用
您仍然必须列出所有可能的类型,但这更好. Where you still have to list all possible types, but it's nicer. 由于所有图像实现都是具有名为 Since all image implementations are struct pointers having a field named 它是这样的: 测试: 输出(在转到游乐场上尝试): 这篇关于将接口声明为其类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!Pix
的字段的结构指针,因此您可以使用反射来获取该字段.此实现将处理将来的图像实现,而无需进行任何更改(如果它们也将是具有Pix
字段的结构).Pix
, you may use reflection to get that field. This implementation will handle future image implementations without any change (if they will also be structs with a Pix
field).func getPix(img image.Image) ([]uint8, error) {
v := reflect.ValueOf(img)
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
if v.Kind() == reflect.Struct {
pv := v.FieldByName("Pix")
if pv.IsValid() {
if pix, ok := pv.Interface().([]uint8); ok {
return pix, nil
}
}
}
return nil, fmt.Errorf("unknown image type %T", img)
}
fmt.Println(getPix(&image.NRGBA{}))
fmt.Println(getPix(&image.RGBA{}))
type unknownImage struct{ image.Image }
fmt.Println(getPix(unknownImage{}))
[] <nil>
[] <nil>
[] unknown image type main.unknownImage