Which is what?
Let’s define another type R
that also implements the interface I
:
type R struct { i int }
func (p *R) Get() int { return p.i }
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.
func f(p I) {
switch t := p.(type) { 1
case *S: 2
case *R: 2
default: 3
}
}
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.
if t, ok := something.(I); ok { 1
// ...
}
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)
.