A
A
Artem00712021-05-26 11:23:57
go
Artem0071, 2021-05-26 11:23:57

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


Here is the code: play
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

1 answer(s)
E
Evgeny Mamonov, 2021-05-26
@Artem0071

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 question

Ask a Question

731 491 924 answers to any question