Jeff Li

Be another Jeff

Test if a value implements an interface in golang

We all know that type assert could be used to cast a interface type variable to its actual type value. In the other way, golang allows you to query if a value has implement an interface. This could be used when writing unit test cases, for example, you want to make sure that a struct actually implements certain interfaces.

  • Assign the value to an empty interface variable

  • Use type assert: assert the empty interface type to any specific interface you are interested

Here is a small while complete example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package main

import (
  . "launchpad.net/gocheck"
  "testing"
)

func Test(t *testing.T) {
  TestingT(t)
}

type MySuite struct{}

var _ = Suite(&MySuite{})

type IFoobar interface {
  foobar()
}

type Foobar struct {
}

func (f *Foobar) foobar() {
}

func (s *MySuite) TestFoobar(c *C) {
  v := Foobar{}
  var i interface{} = v
  _, ok := i.(IFoobar)
  c.Assert(ok, Equals, false)

  var p interface{} = &v
  _, ok = p.(IFoobar)
  c.Assert(ok, Equals, true)
}

Comments