Is it possible to copy the interface as well as the structure?

type MyInterface interface{} myInterface2 := *myInterface 

Now invalid indirect of error

  • it is not clear what you want to achieve? What is the task then? - Darigaaz
  • The question is why the operator (: =) does not work with an interface type variable. If I have a variable of type MyInterface and I want to make a copy with: = but it does not work. But if you create: type MyType struct {} and write: myStruct2: = myStruct, then it works. - TomX01
  • play.golang.org/p/vCEWqVuDh5 but it’s obvious that you want something else and it’s not clear what =) And keep in mind that interface {} is a “reference” type, when you copy it, you create only a new link to the object pointed to by This interface - Darigaaz
  • I think I get it. With myInterface2 := *myInterface compiler does not know what it means to dereference (*) an interface, because it is not a link, but you can tell it explicitly what type there is var myInterface2 interface{} = myInterface.(myType) - Darigaaz

1 answer 1

With myInterface2 := *myInterface compiler does not know what it means to dereference (*) an interface, since this is not a link, but you can tell it explicitly what type it is

 var myInterface2 interface{} = myInterface.(myType) 

If the type is unknown to you, only reflect can help you, but it is slow and leads to a large number of errors =)

https://play.golang.org/p/W43YP7MGSU

 package main import ( "fmt" "reflect" ) type MyStruct struct { N int } type MyInterface interface{} func main() { fmt.Println("Hello, playground") var my_struct_1 MyInterface = MyStruct{N: 1} var my_struct_2 MyInterface = my_struct_1.(MyStruct) fmt.Println(my_struct_1, my_struct_2) t := reflect.TypeOf(my_struct_1) fmt.Println(t) ss2 := reflect.ValueOf(my_struct_1).Convert(t) fmt.Println(ss2) fmt.Printf("%T %#v\n", ss2, ss2) // Увы он останется reflect.Value типом, пока, опять же, не сделаешь явное преобразование ss2.Interface().(MyStruct) ss2_MyStruct := ss2.Interface().(MyStruct) fmt.Printf("%T %#v\n", ss2_MyStruct, ss2_MyStruct) } 
  • Reflection does not fit: slowly. I realized that the compiler does not know about the type and without explicit type conversion copying will not work. I decide through switch instanceof - TomX01