Preface
Based on user feedback, answer the two frequently asked code writing questions go-gin-api
Take the following code snippet as an example:
- Line 8, what does this wording mean?
- In line 11, why define an i() method?
Question one
var _ Signature = (*signature)(nil)
What does this code mean?
Force *signature
to implement the Signature
interface, and the compiler will check *signature
type implements the Signature
interface.
Let's look at 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")
}
Will the above code output hello world
?
Will not!
At this time, it will output:
./main.go:5:5: cannot use (*study)(nil) (type *study) as type Study in assignment:
*study does not implement Study (missing Listen method)
If you remove this line:
var _ Study = (*study)(nil)
At this time, hello world
can be output.
Question two
i()
Why define an i() method in the interface?
Mandatory Signature
interface can only be implemented in this package, and are not allowed to be implemented in other packages. Because there are lowercase methods in the interface, they cannot be implemented in other packages. i() represents a lowercase method, and other names are fine.
Let's look at an example:
package study
type Study interface {
Listen(message string) string
i()
}
func Speak(s Study) string {
return s.Listen("abc")
}
A Study
interface is defined. The interface contains two methods, one of which is i().
Speak
method is defined, the input parameter is the Study
interface, and the method body is the Listen
method in the execution interface.
Next look at another file:
type stu struct {
Name string
}
func (s *stu) Listen(message string) string {
return s.Name + " 听 " + message
}
func (s *stu) i() {}
func main() {
message := study.Speak(new(stu))
fmt.Println(message)
}
A stu
structure is defined. This structure implements the Study
interface. Will the above program output normally?
Will not!
At this time, it will output:
./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()
If you remove the i() in the interface, it will output normally: listen to abc
summary
The above two questions are the most frequently asked questions by readers in the process of learning code.
In addition to the option design pattern, there are many questions. You can read this article: "Do you use the variable parameters of the "
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。