preface
Based on user feedback, answer two frequently asked code writing questions about the open source project: Go-Gin-API.
Take the following code snippet as an example:
- Line 8, what does that mean?
- Line 11, why define an I () method?
Problem a
var _ Signature = (*signature)(nil)
Copy the code
What does this code mean?
If you force *signature to implement the signature interface, the compiler will check if the *signature type implements the signature interface.
Here’s an example:
package main
import "fmt"
var _ Study = (*study)(nil)
type study struct {
Name string
}
type Study interface {
Listen(message string) string
}
func main() {
fmt.Println("hello world")
}
Copy the code
Does the above code print Hello world?
Don’t!
This will print:
./main.go:5:5: cannot use (*study)(nil) (type *study) as type Study in assignment:
*study does not implement Study (missing Listen method)
Copy the code
If I remove this line:
var _ Study = (*study)(nil)
Copy the code
And now you can print Hello World.
Question 2
i()
Copy the code
Why is an I () method defined in an interface?
Force all methods in the Signature interface to be implemented only in this package and not in other packages. Because the interface has lower-case methods, they cannot be implemented in other packages. I () is a lowercase method, or any other name is fine.
Here’s an example:
package study
type Study interface {
Listen(message string) string
i()
}
func Speak(s Study) string {
return s.Listen("abc")
}
Copy the code
Defines a Study interface that contains two methods, including one I ().
Defines a Speak method with the Study interface as its input and the body of the method to Listen in the interface.
Next, look at another file:
Type stu struct {Name string} func (s *stu) Listen(message string) string {return S.name + "Listen" + message} func (s) *stu) i() {} func main() { message := study.Speak(new(stu)) fmt.Println(message) }Copy the code
Defines a STU structure that implements the methods in the Study interface. Does the program output normally?
Don’t!
This will print:
./main.go:19:28: cannot use new(stu) (type *stu) as type study.Study in argument to study.Speak:
*stu does not implement study.Study (missing study.i method)
have i()
want study.i()
Copy the code
If I () is removed from the interface, the following output is displayed: Listen to ABC
summary
These are two of the most common questions that readers ask when learning code, and I hope this will help you solve them.
For example, if a function has an indeterminate parameter, do you use it like this?
Recommended reading
- Understanding of distributed transactions
- Based on consumer feedback, two new features have been added to the open source project Go-Gin-API
- About the process of the order status of the e-commerce system flow, share my technical solution (with source code)
- How do I write Git Commit message?