{"id":796,"date":"2019-12-01T13:52:08","date_gmt":"2019-12-01T13:52:08","guid":{"rendered":"https:\/\/golangbyexamples.com\/?p=796"},"modified":"2019-12-01T13:52:17","modified_gmt":"2019-12-01T13:52:17","slug":"go-check-if-type-implements-interface","status":"publish","type":"post","link":"https:\/\/golangbyexamples.com\/go-check-if-type-implements-interface\/","title":{"rendered":"Go : Check if type implements an interface"},"content":{"rendered":"\n
Sometimes there can be scenarios where it is needed to know if your type satisfies an interface or not. This can be easily achieved using a blank identifier.<\/p>\n\n\n\n
package main\n\ntype shape interface {\n getNumSides() int\n getArea() int\n}\n\ntype square struct {\n len int\n}\n\nfunc (s square) getNumSides() int {\n return 4\n}\n\n\/\/ func (s square) getArea() int {\n\/\/ return s.len * 2\n\/\/ }\n\nfunc main() {\n \/\/Verify that *square implement shape\n var _ shape = square{}\n}<\/code><\/pre>\n\n\n\nIn the above program, we have commented out the square’s getArea() <\/strong>function. On “go build” above program gives the error<\/p>\n\n\n\nmain.go:25:6: cannot use square literal (type square) as type shape in assignment:\n square does not implement shape (missing getArea method)<\/code><\/pre>\n\n\n\nOn uncommenting the getArea() <\/strong>method the error goes away. To check if a pointer of the type implements the interface then it can be done as below<\/p>\n\n\n\nvar _ shape = &square{}<\/code><\/pre>\n\n\n\nOR<\/strong><\/p>\n\n\n\nvar _ shape = (*square)(nil)<\/code><\/pre>\n\n\n\nFirst one will give the error <\/p>\n\n\n\n
main.go:25:6: cannot use (*square)(nil) (type *square) as type shape in assignment:\n *square does not implement shape (missing getArea method)<\/code><\/pre>\n\n\n\nwhile the latter one will give error <\/p>\n\n\n\n
main.go:25:6: cannot use &square literal (type *square) as type shape in assignment:\n *square does not implement shape (missing getArea method)<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"Sometimes there can be scenarios where it is needed to know if your type satisfies an interface or not. This can be easily achieved using a blank identifier. In the above program,…<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"spay_email":"","footnotes":"","jetpack_publicize_message":"","jetpack_is_tweetstorm":false},"categories":[1],"tags":[3,11,99],"class_list":["post-796","post","type-post","status-publish","format-standard","hentry","category-tech","tag-go","tag-interface","tag-type"],"yoast_head":"\n
Go : Check if type implements an interface - Welcome To Golang By Example<\/title>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\n\t\n\t\n