Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass type to function argument in Go

Tags:

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..

like image 223
yountae.kang Avatar asked Jun 29 '18 08:06

yountae.kang


People also ask

How do you pass an argument to a function in Go?

Golang supports two different ways to pass arguments to the function i.e. Pass by Value or Call by Value and Pass By Reference or Call By Reference. By default, Golang uses the call by value way to pass the arguments to the function.

Can you pass type in Golang?

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.

How do you pass variable arguments in Golang?

In Golang, a function that can be called with a variable argument list is known as a variadic function. One can pass zero or more arguments in the variadic function. If the last parameter of a function definition is prefixed by ellipsis …, then the function can accept any number of arguments for that parameter.

What does func () mean in Golang?

func: It is a keyword in Go language, which is used to create a function. function_name: It is the name of the function. Parameter-list: It contains the name and the type of the function parameters. Return_type: It is optional and it contain the types of the values that function returns.


1 Answers

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 
like image 187
icza Avatar answered Oct 16 '22 04:10

icza