0

I'm making a call to os/Create function and want to make sure in one of my test cases that the response is indeed of type *os.File.

Below is my code snippet. Though I made a lot of iterations but the motivation for these lines was this post.

//somevar -- gets *os.File from a function
var varType *os.File
tpe := reflect.TypeOf(varType).Elem()
fmt.Println(reflect.TypeOf(somevar).Implements(tpe)) // I expect a true or false

When I run this code I get a panic:

panic: reflect: non-interface type passed to Type.Implements [recovered]
    panic: reflect: non-interface type passed to Type.Implements

Please suggest what wrong I'm doing. All I want to check for is - some variable is of type *os.File - yes or no.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
  • You cannot check if something implements `os.File` because it is not an interface. What is the type of the variable you want to check? Is it an `interface{}`? If so, you can use a type assertion: `file, ok:=intf.(*os.File)` – Burak Serdar Sep 27 '20 at 21:36
  • The type of the variable I want to check is - *os.File. and I guess its underlying type is a struct. If what I'm doing isn't good, what else could be done to verify something is *os.File type or not? thank you. – user13252132 Sep 27 '20 at 21:42
  • If the type of the variable is `*os.File`, then there is nothing to check. The variable cannot be of any other type, otherwise it would be a compile error. – Burak Serdar Sep 27 '20 at 21:43

1 Answers1

0

I think you may just be looking for

var varType *os.File
tpe := reflect.TypeOf(varType).Elem()
fmt.Println(tpe == reflect.TypeOf(somevar).Elem())
  • This is meaningful only if `somevar` is an interface. Even then, a type-assertion would be much more concise. – Burak Serdar Sep 27 '20 at 23:00
  • Added a type assertion example. I was just answering the question as OP had it. –  Sep 27 '20 at 23:04
  • I still miss the point of this question and the answer. The OP mentions a call to os.Create. That cannot return anything other than *os.File. There is nothing to check. – Burak Serdar Sep 27 '20 at 23:12
  • Yeah on second thought I removed the type assertion example. Because they are clear that it's a concrete type they're testing. They are just being needlessly thorough in testing. –  Sep 27 '20 at 23:16
  • Test with reflection is pointless as well. What is being tested at runtime is something that will fail at compile time if wrong. If a function is declared to return a concrete type like *os.File then there is no point in testing that, it will not return anything else. – Burak Serdar Sep 27 '20 at 23:19
  • Thanks folks for your thoughts and replies - appreciate the help. – user13252132 Sep 28 '20 at 03:59