Golang the method of determining whether to implement the interface interface

Source: Internet
Author: User
This is a created article in which the information may have evolved or changed.

Due to the Golang interface use is very flexible, do not need to display the implementation of the interface interface method, a little dynamic feeling,

Disadvantage: If you do not implement interface method, forcibly converted to interface, run time abnormal error

Workaround: At compile time to throw this error, on the code:

package mainimport ("fmt")type value interface {Show()}type test_value struct{}// func (value *test_value) Show() { fmt.Printf("test \n") }var _ value = new(test_value) // 使用类似方法处理,编译的时候会报错func main() {}// -------------------------------- Error Msg -------------------------------- //./test.go:18: cannot use new(test_value) (type *test_value) as type value in assignment:    *test_value does not implement value (missing Show method)// 如果把接口的方法注释掉,编译的时候就会报错// ------------------- 总结来说 --------------- type T struct{}var _ I = T{}其中 I为interface// 上面用来判断 type T是否实现了I,用作类型断言,如果T没有实现借口I,则编译错误.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.