1

Preface

Based on user feedback, answer the two frequently asked code writing questions go-gin-api GitHub stars

Take the following code snippet as an example:

two.png

  1. Line 8, what does this wording mean?
  2. 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 "

Recommended reading


程序员新亮
2.9k 声望1.2k 粉丝

GitHub 9K+ Star,其中适合 Go 新手的开箱即用项目 go-gin-api 5.2K Star:[链接],联系我:wx-xinliang