Succinctly return a pointer to an interface of a literal in Go - go

Is there a more succinct of casting a literal into an empty interface? A lot of the relevant community issues are about coercing an interface to a literal but not vice versa.
Looking for something of the form:
func pointerInterfaceOf(in interface{}) *interface{} {
return &in
}
I have tried
&reflect.ValueOf(in).Interface() // Compiler error
But that is a compiler error.

If the reflect value is a *interface{}, then use:
return reflect.Value(in).Interface().(*interface{})
If the reflect value is not an pointer to an interface, then the shortest code is:
x := reflect.ValueOf(in).Interface()
return &x
The application cannot use &reflect.ValueOf(in).Interface() because the return value from a function is not addressable.

If you want to cast something to interface{}, just use the normal casting syntax:
interface{}(whatever)

Related

Go: difference between any and interface in varargs [duplicate]

As generics have been released in Go 1.18 pretty recently, I've started learning them. I generally get the concept, because I have some Java experience from the past. But I don't get some implementation specifics.
For instance: when it's more suitable to use any instead of interface{}? Here's an example:
func printInterface(foo interface{}) {
fmt.Printf("%v\n", foo)
}
func printAny[T any](foo T) {
fmt.Printf("%v\n", foo)
}
func (suite *TestSuite) TestString() {
printInterface("foo")
printAny("foo")
}
Both implementations work. However, if I try to print nil with any-version, I'll get a compile-time error:
cannot infer T.
https://go.dev/play/p/0gmU4rhhaOP
And I won't get this error if I try to print nil with interface{}-version.
So what's the use-case for any? When and which benefits does it bring, compared to simply using interface{}?
I'm asking to provide a specific example, where one implementation is objectively more suitable than another and/or where there is a specific benefit that can be evaluated.
Beside any and interface{} being type aliases — hence, equivalent in usage —, there is a practical difference between any as type parameter and any as regular function argument, as in your example.
The difference is that in printAny[T any](foo T) the type of foo is not any/interface{}, but it's T. And T after instantiation is a concrete type, that may or may not be an interface itself. You can then only pass arguments to an instantiated printAny that can be assigned to that concrete type.
How this impacts your code is most evident with multiple arguments. If we change the function signatures a bit:
func printInterface(foo, bar any) {
fmt.Println(foo, bar)
}
func printAny[T any](foo, bar T) {
fmt.Println(foo, bar)
}
After instantiation:
the function printAny accepts any two arguments of the same type — whichever is used to instantiate T
printInterface, which is equivalent to printInterface(foo, bar interface{}) can still accept two arguments of different types, since both would be individually assignable to any/interface{}.
printInterface(12.5, 0.1) // ok
printInterface(12.5, "blah") // ok, int and string individually assignable to any
printAny(10, 20) // ok, T inferred to int, 20 assignable to int
printAny(10, "k") // compiler error, T inferred to int, "k" not assignable to int
printAny[any](10, "k") // ok, T explicitly instantiated to any, int and string assignable to any
printAny(nil, nil) // compiler error, no way to infer T
printAny[any](nil, nil) // ok, T explicitly instantiated to any, nil assignable to any
A playground: https://go.dev/play/p/pDjP986cj96
Note: the generic version cannot be called with nil without explicit type arguments simply because nil alone doesn't carry type information, so the compiler can't infer T. However nil can be normally assigned to variables of interface type.
any is an alias for interface{}. Spec: Interface types:
For convenience, the predeclared type any is an alias for the empty interface.
Since it is an alias, it doesn't matter which one you use. They are one and the same. They are interchangeable. You can replace one with the other, the code will mean the same.
any is shorter and clearer, but only works from Go 1.18.
Since they are interchangeable, this also works:
func printInterface(foo any) {
fmt.Printf("%v\n", foo)
}
The reason why printAny() doesn't work is due to it being a generic function with a type parameter. To use it, it must be instantiated (its type parameter must be assigned with a known type). Trying to call it with nil carries no type information, so instantiation cannot happen, type inference won't work.
If you call it with a nil value that carries type info, it'll work, or if you specify the type param explicitly (try it on the Go Playground):
printAny((*int)(nil))
printAny[*int](nil)
// Or
var r io.Reader
printAny(r)
And as said, any is interchangeable with interface{}, so you'll have the same code if you swap both occurrences (try this one on the Go Playground):
func printInterface(foo any) {
fmt.Printf("%v\n", foo)
}
func printAny[T interface{}](foo T) {
fmt.Printf("%v\n", foo)
}
Your issue is not related to the usage of any/interface{} — whose difference is purely cosmetic — but it is type inference. As you can see from this playground, if you instantiate your function with an explicit type, like printAny[any](nil) it will work.
If you have a function with generic type you need to specify the types. However the go compiler is very smart and can infer some types for you. But nil alone is impossible to infer.

What is the "any" type in Go 1.18?

In Visual Studio Code, the auto-complete tool (which I presume is gopls?) gives the following template:
m.Range(func(key, value any) bool {
})
where m is a sync.Map. the type any is not recognized, but is put there.
What is any? Can I put the type I want and hope Go 1.18 to do implicit type conversion for me? For example:
m.Range(func(k, v string) { ... })
which will give k, v as string inside the callback, without having to do type cast myself?
any is a new predeclared identifier and a type alias of interface{}.
It comes from issue 49884, CL 368254 and commit 2580d0e.
The issue mentions about interface{}/any:
It's not a special design, but a logical consequence of Go's type declaration syntax.
You can use anonymous interfaces with more than zero methods:
func f(a interface{Foo(); Bar()}) {
a.Foo()
a.Bar()
}
Analogous to how you can use anonymous structs anywhere a type is expected:
func f(a struct{Foo int; Bar string}) {
fmt.Println(a.Foo)
fmt.Println(a.Bar)
}
An empty interface just happens to match all types because all types have at least zero methods.
Removing interface{} would mean removing all interface functionality from the language if you want to stay consistent / don't want to introduce a special case.

How to pass type to function argument in Go

ERROR: type CustomStruct is not an expression.
type CustomStruct struct {
}
func getTypeName(t interface{}) string {
rt := reflect.TypeOf(t).Elem()
return rt.Name()
}
getTypeName(CustomStruct)
How can I pass struct type to function without type instance?
This will work
getTypeName((*CustomStruct)(nil))
But I wonder if there is more simple version..
You can't. You can only pass a value, and CustomStruct is not a value but a type. Using a type identifier is a compile-time error.
Usually when a "type" is to be passed, you pass a reflect.Type value which describes the type. This is what you "create" inside your getTypeName(), but then the getTypeName() will have little left to do:
func getTypeName(t reflect.Type) string {
return t.Name()
}
// Calling it:
getTypeName(reflect.TypeOf(CustomStruct{}))
(Also don't forget that this returns an empty string for anonymous types such as []int.)
Another way is to pass a "typed" nil pointer value as you did, but again, you can just as well use a typed nil value to create the reflect.Type too, without creating a value of the type in question, like this:
t := reflect.TypeOf((*CustomStruct)(nil)).Elem()
fmt.Println(t.Name()) // Prints CustomStruct
Lets resurrect this!
The generics proposal for Go got approved, and that's coming, eventually. When this question was first asked, this probably made more sense as a question, but for anyone looking to implement a generics pattern now, I think I've got an alright API for it.
For now, you can't interact with abstract types, but you can interact with methods on the abstract type, and reflect allows you to examine function signatures. For a method, the 0th is the receiver.
type Example struct {int}
type Generic struct{reflect.Type}
func (p Example) Type() {}
func Reflect(generic interface{}) Generic {
real := reflect.TypeOf(generic)
if real.Kind() != reflect.Func || real.NumIn() < 1 {
panic("reflect.Type.In(n) panics if not a func and if n out of bounds")
}
return Generic{real.In(0)}
}
func (g Generic) Make() interface{} {
return reflect.Zero(g.Type).Interface()
}
func main() {
tOfp := Reflect(Example.Type)
fmt.Printf("Name of the type: %v\n", tOfp.Name())
fmt.Printf("Real (initial)value: %v\n", tOfp.Make())
}
Some quick notes:
The structure of "Example" doesn't matter, rather only that it has a method with a non-pointer receiver.
The definition of a type called "Generic" as a struct is to accomplish what I believed OP's actual intent to be.
The above definition of "Generic" is a struct instead of an interface so that it can have its own method set. Defining "Generic" as an interface, and using a methodset specific to each operand-type used with it would make tons of sense.
If you weren't aware, actual generics are coming in Go 1.18. My example above has no linter or compile protection, and will panic at runtime if used incorrectly. It does work, and will let you reason over abstract types while you wait for a native implementation.
Happy Coding!
From Go version 1.18 a new feature Generics has been introduced. In most of the case instead of passing types to function, we can use generics. Then we will also get compile time error instead of runtime error and it's more efficient than reflect also.
Example Code
func HttpGet[T](url, body) T {
var resp T
return T
}
resp := HttpGet[ResponseType]("dummy.example", nil)

In golang, how to type assert an interface{} to a type specified by a reflect.Type?

For example, I have an interface{} named a, and I also have an reflect.Type called elemType. Now, I want to type assert a to elemType, but a.(elemType) can't be compiled successfully. How to fix it?
Sorry for my confusing expression. My meaning is that I get a type from a function, and I want to type assert an interface{} to this type, but this type is stored in a reflect.Type variable.
What I want to do is similar to the code below:
var a interface{}
//do something
func getType() reflect.Type {
var ret reflect.Type
//do something
return ret
}
targetType := getType()
result := a.(targetType)
Consider a standard type assertion in Go:
v := a.(typeName)
Here the compiler can determine the type of the variable v at compile time, and make use of that knowledge when compiling any further statements involving the variable.
With your example of using a refltect.Type variable in the assertion, it would be impossible to determine the type of v, so the code could not be compiled.
If you need to check that a particular interface variable is of a particular type at runtime, you can still do that with the reflect package. For example:
// if elemType is a normal type
if reflect.ValueOf(a).Type() == elemType {
fmt.Println("type matches")
}
// if elemType is an interface, can check if the value implements it
if reflect.ValueOf(a).Type().Implements(elemType) {
fmt.Println("value implements interface")
}
But you will need a concrete type to return back to standard variables. If you've only got a small selection of possible types, perhaps using a type switch might do what you want.

How to convert value type by another value's reflect.Type in Golang

How to convert value type by another value's reflect.Type in Golang
maybe like this:
func Scan(value interface{}, b string) error {
converted := value.(reflect.TypeOf(b)) // do as "value.(string)"
return nil
}
How can do this properly in golang?
The only way to get a typed value out of an interface is to use a type assertion, and the syntax is value.(T) where T is a type. There's a good reason for this, because it makes the type of the type assertion expression computable: value.(T) has type T. If instead, you allowed value.(E) where E is some expression that evaluates to a reflect.Type (which I think is the gist of your question), then the compiler has no way to (in general) statically determine the type of value.(E) since it depends on the result of an arbitrary computation.

Resources