"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > ## How to Convert a Slice of Interfaces to a Compatible Interface Slice in Go?

## How to Convert a Slice of Interfaces to a Compatible Interface Slice in Go?

Published on 2024-11-02
Browse:453

## How to Convert a Slice of Interfaces to a Compatible Interface Slice in Go?

Converting Slices of Interfaces to Compatible Interface Slices

Implementing different interfaces that contain overlapping methods can provide flexibility in programming. However, passing a slice of one interface to a function expecting a different but compatible interface can result in errors. Let's explore how to address this issue in Go.

Suppose we have interfaces A and B, where A includes B. An implementation of A, Impl, satisfies both A and B.

type A interface {
    Close() error
    Read(b []byte) (int, error)
}

type Impl struct {}

func (I Impl) Read(b []byte) (int, error) {
    fmt.Println("In read!")
    return 10, nil
}

func (I Impl) Close() error {
    fmt.Println("I am here!")
    return nil
}

Individual items can be passed across functions with ease. However, attempting to pass slices of A to functions expecting io.Reader may fail.

func single(r io.Reader) {
    fmt.Println("in single")
}

func slice(r []io.Reader) {
    fmt.Println("in slice")
}

im := &Impl{}

// works
single(im)

// FAILS!
list := []A{t}
slice(list)

To resolve this, we can create a new slice of type []io.Reader and populate it with elements from []A. This is the workaround to bypass the limitation and ensure compatibility between different but overlapping interface types.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3