Answer the question
In order to leave comments, you need to log in
Why do we need generics, if it can be simpler?
Who is in the subject, please explain why in golang it is impossible to []something lead to []interface{} :
func remove(slice []interface{}, s interface{}) []interface{} {
return append(slice[:s], slice[s+1:]...)
}
a := []string{"a", "b", "c"}
b := []int{1, 2, 3}
a = remove(a, 2)
b = remove(b, 1)
package main
import (
"fmt"
"strconv"
)
type intf interface {
get() string
}
type i1 string
func (s i1) get() string {
return string(s)
}
type i2 int
func (s i2) get() string {
return strconv.Itoa(int(s))
}
func print1(a []intf) {
for _, i := range a {
fmt.Print(i, "; ")
}
}
func main() {
a := []intf{i1("xyz"), i2(42)}
print1(a)
//b := []i1{i1("xyz")}
//print1(b)
}
Answer the question
In order to leave comments, you need to log in
Go sucks at interface algebra. Just because a struct A implements an interface I does not mean that []A implements []I.
And all because type casting to an interface is a manipulation with a type identifier in a structure. Obviously, you need to replace this identifier in the loop in each element of the slice in order to achieve the desired effect. I would like it to be inlined or somehow processed automatically during compilation, but not yet.
Who is in the subject, please explain why in golang it is impossible to []cast something to []interface{} :
interface{}
it is a separate type and can only accept a slice of that type.slice []interface{}
func remove(slice []interface{}, s interface{}) []interface{} {
return append(slice[:s.(int)], slice[s.(int)+1:]...)
}
func main() {
a := []string{"a", "b", "c"}
// преобразование
ai := make([]interface{}, len(a))
for i, v := range a {
ai[i] = v
}
ai = remove(ai, 2)
b := []int{1, 2, 3}
// преобразование
bi := make([]interface{}, len(b))
for i, v := range b {
bi[i] = v
}
bi = remove(bi, 1)
fmt.Printf("%T: %v\n", ai, ai)
fmt.Printf("%T: %v\n", bi, bi)
}
I mean, why not make it possible.
s []string
i []int
func main() {
b := []i1{i1("xyz")}
bi := make([]intf, len(b))
for i, v := range b {
bi[i] = v
}
print1(bi)
}
Why do we need generics, if it can be simpler?
func main() {
print1([]intf{nil, nil})
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question