0

Why Go doesn't automatically convert between:

package main

import "fmt"

type Any interface{} // Any is an empty interface
type X func(x Any) // X is a function that receives Any

func Y(x X) { // Y is a function that receives X
  x(1)
}

func test(v interface{}) { // test is not considered equal to X
  fmt.Println("called",v)
}

func main() {
  Y(test) // error: cannot use test (type func(interface {})) as type X in argument to Y
}

Also this one:

package main
import "fmt"

type Any interface{}

func X2(a Any) {
  X(a)
} 
func Y2(a interface{}) {
  X2(a) // this is OK
}

func X(a ...Any) {
  fmt.Println(a)
}
func Y(a ...interface{}) { // but this one not ok
  X(a...) // error: cannot use a (type []interface {}) as type []Any in argument to X
}

func main() {
  v := []int{1,2,3}
  X(v)
  Y(v)
}

I was really hopeful that interface{} could be renamed to Any on anything (slices, map, func) not just simple types

Second question would be: is there a way to make it possible?

Kokizzu
  • 24,974
  • 37
  • 137
  • 233
  • 1
    The lack of implicit casts between named<->unnamed probably feels inconvenient right here. It does mean, though that if you pass both filesizes and flags as `int64`s, you can declare `type Flags uint64` so that the type system will catch if you accidentally swap them. – twotwotwo Dec 05 '14 at 18:29

1 Answers1

5

The first one is about type conversion and type identity, for which you have a set of rules.
See more at "Why can I type alias functions and use them without casting?"

  • type Any interface{} is a named type
  • interface{} is an unnamed type

Their identity is different, and you cannot use func(interface[}) in place of func(Any).


The second one is covered by the golang faq

Can I convert a []T to an []interface{}?

Not directly, because they do not have the same representation in memory.
It is necessary to copy the elements individually to the destination slice. This example converts a slice of int to a slice of interface{}:

t := []int{1, 2, 3, 4}
s := make([]interface{}, len(t))
for i, v := range t {
    s[i] = v
}

See "what is the meaning of interface{} in golang?" for more on the memory representation:

interface

Community
  • 1
  • 1
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250