go-interface

How to cast nil interface to nil other interface

蓝咒 提交于 2020-05-30 09:36:52
问题 I have a classic Go nil interface issue. I'm trying to assert an interface{} , which I assign from a nil error , back to an error interface. That sentence is confusing so I have a handy-dandy example: https://play.golang.com/p/Qhv7197oIE_z package main import ( "fmt" ) func preferredWay(i interface{}) error { return i.(error) } func workAround(i interface{}) error { if i == nil { return nil } return i.(error) } func main() { var nilErr error fmt.Println(workAround(nilErr)) // Prints "<nil>"

Assert interface to its type

烈酒焚心 提交于 2020-01-03 19:08:46
问题 I can't gracefully get pixels of an image as array in general case. f, err := os.Open(imgPath) check(err) defer f.Close() img, _, err := image.Decode(bufio.NewReader(f)) check(err) pixels, err := getPixels(img) check(err) // Logic with pixels. Now function getPixels looks like this: func getPixels(img image.Image) ([]uint8, error) { if i, ok := img.(*image.NRGBA); ok { return i.Pix, nil } else if i, ok := img.(*image.Alpha); ok { return i.Pix, nil } else if i, ok := img.(*image.Alpha16); ok {

Interfaces and pointer receivers

我们两清 提交于 2019-12-22 05:23:36
问题 I am newbie gopher and trying to get my head around the pointer receivers and interfaces. type Foo interface { foo() } type Bar struct {} func (b *Bar) foo() {} based on the above definitions.. --- Allowed --------- b := Bar{} b.foo() --- Not allowed ----- var foo Foo = Bar{} Get compiler error: cannot use Bar literal (type Bar) as type Foo in assignment: Bar does not implement Foo (foo method has pointer receiver) I understand that compiler is doing some pointer conversion and de-referencing

Interfaces and pointer receivers

女生的网名这么多〃 提交于 2019-12-05 07:30:41
I am newbie gopher and trying to get my head around the pointer receivers and interfaces. type Foo interface { foo() } type Bar struct {} func (b *Bar) foo() {} based on the above definitions.. --- Allowed --------- b := Bar{} b.foo() --- Not allowed ----- var foo Foo = Bar{} Get compiler error: cannot use Bar literal (type Bar) as type Foo in assignment: Bar does not implement Foo (foo method has pointer receiver) I understand that compiler is doing some pointer conversion and de-referencing on our behalf in the first scenario. Why doesn't it do the same thing in the second scenario ? Naveen

Type converting slices of interfaces

余生长醉 提交于 2019-11-25 22:08:29
问题 I\'m curious why Go does\'t implicitly convert []T to []interface{} when it will implicitly convert T to interface{} . Is there something non-trivial about this conversion that I\'m missing? Example: func foo([]interface{}) { /* do something */ } func main() { var a []string = []string{\"hello\", \"world\"} foo(a) } go build complains cannot use a (type []string) as type []interface {} in function argument And if I try to do it explicitly, same thing: b := []interface{}(a) complains cannot