Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

go - Allowing multiple types in arguments to interface method


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To implement an interface, a type has to implement the methods of the interface. The method MyFunc(interface{}) is different from MyFunc(string), so a type implementing MyFunc(string) does not implement the interface with the method with interface{} arg.

The semantics of the method that takes a string is different from the one that takes an interface{}. First, the method that takes a string cannot get a nil-value, but the one that gets an interface{} does. The calling semantics are also different: To call a function with interface{} argument, the compiler creates an interface{} containing the value and the type of the value you're calling it with. Finally, A type with MyFunc(string) cannot be substituted for a type with MyFunc(interface{}), because the second one can be called with any type of data.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...