-3

For example, we can return any on the interface like this:

type AnyFunc interface {
    Execute() any
}

type MyStruct struct {
    Value int
}

func (m MyStruct) Execute() any {
    return m.Value
}

My understanding is to use the return any you would still need to do a run time type check. What is the functional difference from interface{} then?

What is actually returned at runtime? Like with interface{}, I can expect a value pointing the concrete type, and then type /casting checking works like it does in Java (although I don't know how that would work with go's primitives). But then what is returned with the any type?

If you say it's whatever the underlying type is, then how does the compiler know how much memory to allocate for the object? Only way it could do that is it knew the the type of the object ahead of time. If it knows the type of the object ahead of time, then why do we need a runtime type check.

Thomas
  • 6,032
  • 6
  • 41
  • 79
  • The compiler does not know how much memory to allocate for an object of type any. This is because the type any can hold any value of any type. The compiler can only know the size of the object when it is used. For example, if an any object is used to store a string, the compiler will know that the object needs to be at least as large as a string. However, if an any object is used to store a struct, the compiler will not know how much memory to allocate for the struct. This is because the size of a struct can vary depending on the fields that are defined in the struct. – Vishwa Ratna Aug 14 '23 at 06:01
  • 2
    Between `any` and `interface{}` there is no difference whatsoever other than the number of key strokes needed to type out each type. – mkopriva Aug 14 '23 at 07:09

0 Answers0