Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

usage of interface{} on a struct to check if it satisfies an interface in golang

Tags:

interface

go

Given the following code:

package main

import (
    "fmt"
)

type work interface {
    filter() bool
}

type organ struct {
    name string
}

func (s *organ) filter () bool {
    return true;
}


func main() {
    kidney := &organ {
            name : "kidney",    
        }

    _, ok := interface{}(kidney).(work)
    fmt.Println(ok);
}

I did not fully get the following part:

_, ok := interface{}(kidney).(work)

It seems to me, it is converting struct to the interface{} type, which I understand, but why is it required to convert to an interface{} type to check if it satisfies another interface. More specifically, why the following code fails?

ok := kidney.(work)

with error

invalid type assertion: kidney.(work) (non-interface type *organ on left)

like image 277
soupybionics Avatar asked Mar 11 '23 18:03

soupybionics


1 Answers

TL;DR If you always know the concrete type (e.g., kidney), then you don't need a type assertion; just pass it into your work variable and carry on--the compiler will guarantee that kidney satisfies the work interface, otherwise your program won't compile.

The reason you must first convert the concrete type into an interface{} is because type assertions (i.e., dynamic type checks) only make sense between dynamic types (i.e., interfaces). It doesn't make sense to do a runtime type check on a thing the compiler can guarantee at compile time. Hopefully this makes sense?

like image 82
weberc2 Avatar answered Mar 13 '23 08:03

weberc2