Answer the question
In order to leave comments, you need to log in
Why it is impossible to return so structure?
Why can't a function that must return an interface return a structure that implements that interface itself? Or is it possible in some other way? Or is something not right at all? I'm kind of confused..
cannot use a (type []a) as type []IA in return argument
package main
type IA interface {
GetName() string
}
type a struct {
}
func (r a) GetName() string {
return "name"
}
func main() {
getA()
}
func getA() []IA {
var a = make([]a, 10)
return a
}
Answer the question
In order to leave comments, you need to log in
In real life, most likely, the task will have to be solved a little differently.
Usually you receive data in the form of structures, for example, when you retrieve data from a database.
At the time of receiving data, you just need to fill the slice of interfaces with these structures (which implement the methods of the interface)
Made an example of how the task can be solved
https://play.golang.org/p/RKrCLIqakXg
package main
import "fmt"
// объявляем интерфейс
type Profile interface {
GetFullName() string
}
// структура данных, которая будет реализовывать интерфейс Profile
type User struct {
Name string
LastName string
}
// реализация метода интерфейса Profile
func (u User) GetFullName() string {
return u.Name + ` ` + u.LastName
}
// пример функции, которая извлекает/формирует данные и возвращает слайс интерфейсов
func getProfiles() []Profile {
// создаём слайс интерфейсов
var result = make([]Profile, 10)
for i := 0; i<10; i++ {
// но заполняем слайс структурами, которые реализуют этот интерфейс
result[i] = User{
Name: fmt.Sprintf("Name%d", i),
LastName: fmt.Sprintf("LastName%d", i),
}
}
return result
}
// пример функции, которая работает со слайсом интерфейсов.
func printProfiles(profiles []Profile) {
for _, profile := range profiles {
fmt.Println(profile.GetFullName())
}
}
func main() {
printProfiles(getProfiles())
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question