Which is what?

Let’s define another type R that also implements the interface I:

  1. type R struct { i int }
  2. func (p *R) Get() int { return p.i }
  3. func (p *R) Put(v int) { p.i = v }

The function f can now accept variables of type R and S.

Suppose you need to know the actual type in the function f. In Go you canfigure that out by using a type switch.

  1. func f(p I) {
  2. switch t := p.(type) { 1
  3. case *S: 2
  4. case *R: 2
  5. default: 3
  6. }
  7. }

At 1 we use the type switch, note that the .(type) syntax is only validwithin a switch statement. We store the value in the variable t. Thesubsequent cases 2 each check for a different actual type. And we can evenhave a default 3 clause. It is worth pointing out that both case R andcase s aren’t possible, because p needs to be a pointer in order to satisfyi.

A type switch isn’t the only way to discover the type at run-time.

  1. if t, ok := something.(I); ok { 1
  2. // ...
  3. }

You can also use a “comma, ok” form 1 to see if an interface type implementsa specific interface. If ok is true, t will hold the type of something.When you are sure a variable implements an interface you can use: t := something.(I) .